]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
574f4e32519b3bb5b189183422fb3fb4dbf37c0a
[openldap] / servers / slapd / overlays / syncprov.c
1 /* $OpenLDAP$ */
2 /* syncprov.c - syncrepl provider */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2004-2009 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS:
17  * This work was initially developed by Howard Chu for inclusion in
18  * OpenLDAP Software.
19  */
20
21 #include "portable.h"
22
23 #ifdef SLAPD_OVER_SYNCPROV
24
25 #include <ac/string.h>
26 #include "lutil.h"
27 #include "slap.h"
28 #include "config.h"
29 #include "ldap_rq.h"
30
31 #ifdef LDAP_DEVEL
32 #define CHECK_CSN       1
33 #endif
34
35 /* A modify request on a particular entry */
36 typedef struct modinst {
37         struct modinst *mi_next;
38         Operation *mi_op;
39 } modinst;
40
41 typedef struct modtarget {
42         struct modinst *mt_mods;
43         struct modinst *mt_tail;
44         Operation *mt_op;
45         ldap_pvt_thread_mutex_t mt_mutex;
46 } modtarget;
47
48 /* A queued result of a persistent search */
49 typedef struct syncres {
50         struct syncres *s_next;
51         struct berval s_dn;
52         struct berval s_ndn;
53         struct berval s_uuid;
54         struct berval s_csn;
55         char s_mode;
56         char s_isreference;
57 } syncres;
58
59 /* Record of a persistent search */
60 typedef struct syncops {
61         struct syncops *s_next;
62         struct berval   s_base;         /* ndn of search base */
63         ID              s_eid;          /* entryID of search base */
64         Operation       *s_op;          /* search op */
65         int             s_rid;
66         int             s_sid;
67         struct berval s_filterstr;
68         int             s_flags;        /* search status */
69 #define PS_IS_REFRESHING        0x01
70 #define PS_IS_DETACHED          0x02
71 #define PS_WROTE_BASE           0x04
72 #define PS_FIND_BASE            0x08
73 #define PS_FIX_FILTER           0x10
74 #define PS_TASK_QUEUED          0x20
75
76         int             s_inuse;        /* reference count */
77         struct syncres *s_res;
78         struct syncres *s_restail;
79         ldap_pvt_thread_mutex_t s_mutex;
80 } syncops;
81
82 /* A received sync control */
83 typedef struct sync_control {
84         struct sync_cookie sr_state;
85         int sr_rhint;
86 } sync_control;
87
88 #if 0 /* moved back to slap.h */
89 #define o_sync  o_ctrlflag[slap_cids.sc_LDAPsync]
90 #endif
91 /* o_sync_mode uses data bits of o_sync */
92 #define o_sync_mode     o_ctrlflag[slap_cids.sc_LDAPsync]
93
94 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
95 #define SLAP_SYNC_REFRESH                               (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
96 #define SLAP_SYNC_PERSIST                               (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
97 #define SLAP_SYNC_REFRESH_AND_PERSIST   (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
98
99 /* Record of which searches matched at premodify step */
100 typedef struct syncmatches {
101         struct syncmatches *sm_next;
102         syncops *sm_op;
103 } syncmatches;
104
105 /* Session log data */
106 typedef struct slog_entry {
107         struct slog_entry *se_next;
108         struct berval se_uuid;
109         struct berval se_csn;
110         int     se_sid;
111         ber_tag_t       se_tag;
112 } slog_entry;
113
114 typedef struct sessionlog {
115         struct berval   sl_mincsn;
116         int             sl_num;
117         int             sl_size;
118         slog_entry *sl_head;
119         slog_entry *sl_tail;
120         ldap_pvt_thread_mutex_t sl_mutex;
121 } sessionlog;
122
123 /* The main state for this overlay */
124 typedef struct syncprov_info_t {
125         syncops         *si_ops;
126         BerVarray       si_ctxcsn;      /* ldapsync context */
127         int             *si_sids;
128         int             si_numcsns;
129         int             si_chkops;      /* checkpointing info */
130         int             si_chktime;
131         int             si_numops;      /* number of ops since last checkpoint */
132         int             si_nopres;      /* Skip present phase */
133         int             si_usehint;     /* use reload hint */
134         time_t  si_chklast;     /* time of last checkpoint */
135         Avlnode *si_mods;       /* entries being modified */
136         sessionlog      *si_logs;
137         ldap_pvt_thread_rdwr_t  si_csn_rwlock;
138         ldap_pvt_thread_mutex_t si_ops_mutex;
139         ldap_pvt_thread_mutex_t si_mods_mutex;
140 } syncprov_info_t;
141
142 typedef struct opcookie {
143         slap_overinst *son;
144         syncmatches *smatches;
145         struct berval sdn;      /* DN of entry, for deletes */
146         struct berval sndn;
147         struct berval suuid;    /* UUID of entry */
148         struct berval sctxcsn;
149         short ssid;     /* sid of op csn */
150         short sreference;       /* Is the entry a reference? */
151 } opcookie;
152
153 typedef struct fbase_cookie {
154         struct berval *fdn;     /* DN of a modified entry, for scope testing */
155         syncops *fss;   /* persistent search we're testing against */
156         int fbase;      /* if TRUE we found the search base and it's still valid */
157         int fscope;     /* if TRUE then fdn is within the psearch scope */
158 } fbase_cookie;
159
160 static AttributeName csn_anlist[3];
161 static AttributeName uuid_anlist[2];
162
163 /* Build a LDAPsync intermediate state control */
164 static int
165 syncprov_state_ctrl(
166         Operation       *op,
167         SlapReply       *rs,
168         Entry           *e,
169         int             entry_sync_state,
170         LDAPControl     **ctrls,
171         int             num_ctrls,
172         int             send_cookie,
173         struct berval   *cookie )
174 {
175         Attribute* a;
176         int ret;
177
178         BerElementBuffer berbuf;
179         BerElement *ber = (BerElement *)&berbuf;
180
181         struct berval   entryuuid_bv = BER_BVNULL;
182
183         ber_init2( ber, 0, LBER_USE_DER );
184         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
185
186         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
187
188         for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
189                 AttributeDescription *desc = a->a_desc;
190                 if ( desc == slap_schema.si_ad_entryUUID ) {
191                         entryuuid_bv = a->a_nvals[0];
192                         break;
193                 }
194         }
195
196         /* FIXME: what if entryuuid is NULL or empty ? */
197
198         if ( send_cookie && cookie ) {
199                 ber_printf( ber, "{eOON}",
200                         entry_sync_state, &entryuuid_bv, cookie );
201         } else {
202                 ber_printf( ber, "{eON}",
203                         entry_sync_state, &entryuuid_bv );
204         }
205
206         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
207         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
208         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
209
210         ber_free_buf( ber );
211
212         if ( ret < 0 ) {
213                 Debug( LDAP_DEBUG_TRACE,
214                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
215                         0, 0, 0 );
216                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
217                 return ret;
218         }
219
220         return LDAP_SUCCESS;
221 }
222
223 /* Build a LDAPsync final state control */
224 static int
225 syncprov_done_ctrl(
226         Operation       *op,
227         SlapReply       *rs,
228         LDAPControl     **ctrls,
229         int                     num_ctrls,
230         int                     send_cookie,
231         struct berval *cookie,
232         int                     refreshDeletes )
233 {
234         int ret;
235         BerElementBuffer berbuf;
236         BerElement *ber = (BerElement *)&berbuf;
237
238         ber_init2( ber, NULL, LBER_USE_DER );
239         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
240
241         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
242
243         ber_printf( ber, "{" );
244         if ( send_cookie && cookie ) {
245                 ber_printf( ber, "O", cookie );
246         }
247         if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
248                 ber_printf( ber, "b", refreshDeletes );
249         }
250         ber_printf( ber, "N}" );
251
252         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
253         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
254         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
255
256         ber_free_buf( ber );
257
258         if ( ret < 0 ) {
259                 Debug( LDAP_DEBUG_TRACE,
260                         "syncprov_done_ctrl: ber_flatten2 failed\n",
261                         0, 0, 0 );
262                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
263                 return ret;
264         }
265
266         return LDAP_SUCCESS;
267 }
268
269 static int
270 syncprov_sendinfo(
271         Operation       *op,
272         SlapReply       *rs,
273         int                     type,
274         struct berval *cookie,
275         int                     refreshDone,
276         BerVarray       syncUUIDs,
277         int                     refreshDeletes )
278 {
279         BerElementBuffer berbuf;
280         BerElement *ber = (BerElement *)&berbuf;
281         struct berval rspdata;
282
283         int ret;
284
285         ber_init2( ber, NULL, LBER_USE_DER );
286         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
287
288         if ( type ) {
289                 switch ( type ) {
290                 case LDAP_TAG_SYNC_NEW_COOKIE:
291                         ber_printf( ber, "tO", type, cookie );
292                         break;
293                 case LDAP_TAG_SYNC_REFRESH_DELETE:
294                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
295                         ber_printf( ber, "t{", type );
296                         if ( cookie ) {
297                                 ber_printf( ber, "O", cookie );
298                         }
299                         if ( refreshDone == 0 ) {
300                                 ber_printf( ber, "b", refreshDone );
301                         }
302                         ber_printf( ber, "N}" );
303                         break;
304                 case LDAP_TAG_SYNC_ID_SET:
305                         ber_printf( ber, "t{", type );
306                         if ( cookie ) {
307                                 ber_printf( ber, "O", cookie );
308                         }
309                         if ( refreshDeletes == 1 ) {
310                                 ber_printf( ber, "b", refreshDeletes );
311                         }
312                         ber_printf( ber, "[W]", syncUUIDs );
313                         ber_printf( ber, "N}" );
314                         break;
315                 default:
316                         Debug( LDAP_DEBUG_TRACE,
317                                 "syncprov_sendinfo: invalid syncinfo type (%d)\n",
318                                 type, 0, 0 );
319                         return LDAP_OTHER;
320                 }
321         }
322
323         ret = ber_flatten2( ber, &rspdata, 0 );
324
325         if ( ret < 0 ) {
326                 Debug( LDAP_DEBUG_TRACE,
327                         "syncprov_sendinfo: ber_flatten2 failed\n",
328                         0, 0, 0 );
329                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
330                 return ret;
331         }
332
333         rs->sr_rspoid = LDAP_SYNC_INFO;
334         rs->sr_rspdata = &rspdata;
335         send_ldap_intermediate( op, rs );
336         rs->sr_rspdata = NULL;
337         ber_free_buf( ber );
338
339         return LDAP_SUCCESS;
340 }
341
342 /* Find a modtarget in an AVL tree */
343 static int
344 sp_avl_cmp( const void *c1, const void *c2 )
345 {
346         const modtarget *m1, *m2;
347         int rc;
348
349         m1 = c1; m2 = c2;
350         rc = m1->mt_op->o_req_ndn.bv_len - m2->mt_op->o_req_ndn.bv_len;
351
352         if ( rc ) return rc;
353         return ber_bvcmp( &m1->mt_op->o_req_ndn, &m2->mt_op->o_req_ndn );
354 }
355
356 /* syncprov_findbase:
357  *   finds the true DN of the base of a search (with alias dereferencing) and
358  * checks to make sure the base entry doesn't get replaced with a different
359  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
360  * change is detected, any persistent search on this base must be terminated /
361  * reloaded.
362  *   On the first call, we just save the DN and entryID. On subsequent calls
363  * we compare the DN and entryID with the saved values.
364  */
365 static int
366 findbase_cb( Operation *op, SlapReply *rs )
367 {
368         slap_callback *sc = op->o_callback;
369
370         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
371                 fbase_cookie *fc = sc->sc_private;
372
373                 /* If no entryID, we're looking for the first time.
374                  * Just store whatever we got.
375                  */
376                 if ( fc->fss->s_eid == NOID ) {
377                         fc->fbase = 2;
378                         fc->fss->s_eid = rs->sr_entry->e_id;
379                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
380
381                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
382                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
383
384                 /* OK, the DN is the same and the entryID is the same. */
385                         fc->fbase = 1;
386                 }
387         }
388         if ( rs->sr_err != LDAP_SUCCESS ) {
389                 Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err,0,0 );
390         }
391         return LDAP_SUCCESS;
392 }
393
394 static Filter generic_filter = { LDAP_FILTER_PRESENT, { 0 }, NULL };
395 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
396
397 static int
398 syncprov_findbase( Operation *op, fbase_cookie *fc )
399 {
400         /* Use basic parameters from syncrepl search, but use
401          * current op's threadctx / tmpmemctx
402          */
403         ldap_pvt_thread_mutex_lock( &fc->fss->s_mutex );
404         if ( fc->fss->s_flags & PS_FIND_BASE ) {
405                 slap_callback cb = {0};
406                 Operation fop;
407                 SlapReply frs = { REP_RESULT };
408                 int rc;
409
410                 fc->fss->s_flags ^= PS_FIND_BASE;
411                 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
412
413                 fop = *fc->fss->s_op;
414
415                 fop.o_bd = fop.o_bd->bd_self;
416                 fop.o_hdr = op->o_hdr;
417                 fop.o_time = op->o_time;
418                 fop.o_tincr = op->o_tincr;
419
420                 cb.sc_response = findbase_cb;
421                 cb.sc_private = fc;
422
423                 fop.o_sync_mode = 0;    /* turn off sync mode */
424                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
425                 fop.o_callback = &cb;
426                 fop.o_tag = LDAP_REQ_SEARCH;
427                 fop.ors_scope = LDAP_SCOPE_BASE;
428                 fop.ors_limit = NULL;
429                 fop.ors_slimit = 1;
430                 fop.ors_tlimit = SLAP_NO_LIMIT;
431                 fop.ors_attrs = slap_anlist_no_attrs;
432                 fop.ors_attrsonly = 1;
433                 fop.ors_filter = &generic_filter;
434                 fop.ors_filterstr = generic_filterstr;
435
436                 rc = fop.o_bd->be_search( &fop, &frs );
437         } else {
438                 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
439                 fc->fbase = 1;
440         }
441
442         /* After the first call, see if the fdn resides in the scope */
443         if ( fc->fbase == 1 ) {
444                 switch ( fc->fss->s_op->ors_scope ) {
445                 case LDAP_SCOPE_BASE:
446                         fc->fscope = dn_match( fc->fdn, &fc->fss->s_base );
447                         break;
448                 case LDAP_SCOPE_ONELEVEL: {
449                         struct berval pdn;
450                         dnParent( fc->fdn, &pdn );
451                         fc->fscope = dn_match( &pdn, &fc->fss->s_base );
452                         break; }
453                 case LDAP_SCOPE_SUBTREE:
454                         fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base );
455                         break;
456                 case LDAP_SCOPE_SUBORDINATE:
457                         fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base ) &&
458                                 !dn_match( fc->fdn, &fc->fss->s_base );
459                         break;
460                 }
461         }
462
463         if ( fc->fbase )
464                 return LDAP_SUCCESS;
465
466         /* If entryID has changed, then the base of this search has
467          * changed. Invalidate the psearch.
468          */
469         return LDAP_NO_SUCH_OBJECT;
470 }
471
472 /* syncprov_findcsn:
473  *   This function has three different purposes, but they all use a search
474  * that filters on entryCSN so they're combined here.
475  * 1: at startup time, after a contextCSN has been read from the database,
476  * we search for all entries with CSN >= contextCSN in case the contextCSN
477  * was not checkpointed at the previous shutdown.
478  *
479  * 2: when the current contextCSN is known and we have a sync cookie, we search
480  * for one entry with CSN = the cookie CSN. If not found, try <= cookie CSN.
481  * If an entry is found, the cookie CSN is valid, otherwise it is stale.
482  *
483  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
484  * CSN, and generate Present records for them. We always collect this result
485  * in SyncID sets, even if there's only one match.
486  */
487 typedef enum find_csn_t {
488         FIND_MAXCSN     = 1,
489         FIND_CSN        = 2,
490         FIND_PRESENT    = 3
491 } find_csn_t;
492
493 static int
494 findmax_cb( Operation *op, SlapReply *rs )
495 {
496         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
497                 struct berval *maxcsn = op->o_callback->sc_private;
498                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
499                         slap_schema.si_ad_entryCSN );
500
501                 if ( a && ber_bvcmp( &a->a_vals[0], maxcsn ) > 0 &&
502                         slap_parse_csn_sid( &a->a_vals[0] ) == slap_serverID ) {
503                         maxcsn->bv_len = a->a_vals[0].bv_len;
504                         strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
505                 }
506         }
507         return LDAP_SUCCESS;
508 }
509
510 static int
511 findcsn_cb( Operation *op, SlapReply *rs )
512 {
513         slap_callback *sc = op->o_callback;
514
515         /* We just want to know that at least one exists, so it's OK if
516          * we exceed the unchecked limit.
517          */
518         if ( rs->sr_err == LDAP_ADMINLIMIT_EXCEEDED ||
519                 (rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS )) {
520                 sc->sc_private = (void *)1;
521         }
522         return LDAP_SUCCESS;
523 }
524
525 /* Build a list of entryUUIDs for sending in a SyncID set */
526
527 #define UUID_LEN        16
528
529 typedef struct fpres_cookie {
530         int num;
531         BerVarray uuids;
532         char *last;
533 } fpres_cookie;
534
535 static int
536 findpres_cb( Operation *op, SlapReply *rs )
537 {
538         slap_callback *sc = op->o_callback;
539         fpres_cookie *pc = sc->sc_private;
540         Attribute *a;
541         int ret = SLAP_CB_CONTINUE;
542
543         switch ( rs->sr_type ) {
544         case REP_SEARCH:
545                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
546                 if ( a ) {
547                         pc->uuids[pc->num].bv_val = pc->last;
548                         AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
549                                 pc->uuids[pc->num].bv_len );
550                         pc->num++;
551                         pc->last = pc->uuids[pc->num].bv_val;
552                         pc->uuids[pc->num].bv_val = NULL;
553                 }
554                 ret = LDAP_SUCCESS;
555                 if ( pc->num != SLAP_SYNCUUID_SET_SIZE )
556                         break;
557                 /* FALLTHRU */
558         case REP_RESULT:
559                 ret = rs->sr_err;
560                 if ( pc->num ) {
561                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
562                                 0, pc->uuids, 0 );
563                         pc->uuids[pc->num].bv_val = pc->last;
564                         pc->num = 0;
565                         pc->last = pc->uuids[0].bv_val;
566                 }
567                 break;
568         default:
569                 break;
570         }
571         return ret;
572 }
573
574 static int
575 syncprov_findcsn( Operation *op, find_csn_t mode )
576 {
577         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
578         syncprov_info_t         *si = on->on_bi.bi_private;
579
580         slap_callback cb = {0};
581         Operation fop;
582         SlapReply frs = { REP_RESULT };
583         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
584         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
585         struct berval maxcsn;
586         Filter cf;
587         AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
588         fpres_cookie pcookie;
589         sync_control *srs = NULL;
590         struct slap_limits_set fc_limits;
591         int i, rc = LDAP_SUCCESS, findcsn_retry = 1;
592         int maxid;
593
594         if ( mode != FIND_MAXCSN ) {
595                 srs = op->o_controls[slap_cids.sc_LDAPsync];
596         }
597
598         fop = *op;
599         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
600         /* We want pure entries, not referrals */
601         fop.o_managedsait = SLAP_CONTROL_CRITICAL;
602
603         cf.f_ava = &eq;
604         cf.f_av_desc = slap_schema.si_ad_entryCSN;
605         BER_BVZERO( &cf.f_av_value );
606         cf.f_next = NULL;
607
608         fop.o_callback = &cb;
609         fop.ors_limit = NULL;
610         fop.ors_tlimit = SLAP_NO_LIMIT;
611         fop.ors_filter = &cf;
612         fop.ors_filterstr.bv_val = buf;
613
614 again:
615         switch( mode ) {
616         case FIND_MAXCSN:
617                 cf.f_choice = LDAP_FILTER_GE;
618                 /* If there are multiple CSNs, use the one with our serverID */
619                 for ( i=0; i<si->si_numcsns; i++) {
620                         if ( slap_serverID == si->si_sids[i] ) {
621                                 maxid = i;
622                                 break;
623                         }
624                 }
625                 if ( i == si->si_numcsns ) {
626                         /* No match: this is multimaster, and none of the content in the DB
627                          * originated locally. Treat like no CSN.
628                          */
629                         return LDAP_NO_SUCH_OBJECT;
630                 }
631                 cf.f_av_value = si->si_ctxcsn[maxid];
632                 fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
633                         "(entryCSN>=%s)", cf.f_av_value.bv_val );
634                 if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
635                         return LDAP_OTHER;
636                 }
637                 fop.ors_attrsonly = 0;
638                 fop.ors_attrs = csn_anlist;
639                 fop.ors_slimit = SLAP_NO_LIMIT;
640                 cb.sc_private = &maxcsn;
641                 cb.sc_response = findmax_cb;
642                 strcpy( cbuf, cf.f_av_value.bv_val );
643                 maxcsn.bv_val = cbuf;
644                 maxcsn.bv_len = cf.f_av_value.bv_len;
645                 break;
646         case FIND_CSN:
647                 if ( BER_BVISEMPTY( &cf.f_av_value )) {
648                         cf.f_av_value = srs->sr_state.ctxcsn[0];
649                         /* If there are multiple CSNs, use the smallest */
650                         for ( i=1; i<srs->sr_state.numcsns; i++ ) {
651                                 if ( ber_bvcmp( &cf.f_av_value, &srs->sr_state.ctxcsn[i] )
652                                         > 0 ) {
653                                         cf.f_av_value = srs->sr_state.ctxcsn[i];
654                                 }
655                         }
656                 }
657                 /* Look for exact match the first time */
658                 if ( findcsn_retry ) {
659                         cf.f_choice = LDAP_FILTER_EQUALITY;
660                         fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
661                                 "(entryCSN=%s)", cf.f_av_value.bv_val );
662                 /* On retry, look for <= */
663                 } else {
664                         cf.f_choice = LDAP_FILTER_LE;
665                         fop.ors_limit = &fc_limits;
666                         memset( &fc_limits, 0, sizeof( fc_limits ));
667                         fc_limits.lms_s_unchecked = 1;
668                         fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
669                                 "(entryCSN<=%s)", cf.f_av_value.bv_val );
670                 }
671                 if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
672                         return LDAP_OTHER;
673                 }
674                 fop.ors_attrsonly = 1;
675                 fop.ors_attrs = slap_anlist_no_attrs;
676                 fop.ors_slimit = 1;
677                 cb.sc_private = NULL;
678                 cb.sc_response = findcsn_cb;
679                 break;
680         case FIND_PRESENT:
681                 fop.ors_filter = op->ors_filter;
682                 fop.ors_filterstr = op->ors_filterstr;
683                 fop.ors_attrsonly = 0;
684                 fop.ors_attrs = uuid_anlist;
685                 fop.ors_slimit = SLAP_NO_LIMIT;
686                 cb.sc_private = &pcookie;
687                 cb.sc_response = findpres_cb;
688                 pcookie.num = 0;
689
690                 /* preallocate storage for a full set */
691                 pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
692                         sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
693                         op->o_tmpmemctx );
694                 pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
695                 pcookie.uuids[0].bv_val = pcookie.last;
696                 pcookie.uuids[0].bv_len = UUID_LEN;
697                 for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
698                         pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
699                         pcookie.uuids[i].bv_len = UUID_LEN;
700                 }
701                 break;
702         }
703
704         fop.o_bd->bd_info = (BackendInfo *)on->on_info;
705         fop.o_bd->be_search( &fop, &frs );
706         fop.o_bd->bd_info = (BackendInfo *)on;
707
708         switch( mode ) {
709         case FIND_MAXCSN:
710                 if ( ber_bvcmp( &si->si_ctxcsn[maxid], &maxcsn )) {
711 #ifdef CHECK_CSN
712                         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
713                         assert( !syn->ssyn_validate( syn, &maxcsn ));
714 #endif
715                         ber_bvreplace( &si->si_ctxcsn[maxid], &maxcsn );
716                         si->si_numops++;        /* ensure a checkpoint */
717                 }
718                 break;
719         case FIND_CSN:
720                 /* If matching CSN was not found, invalidate the context. */
721                 if ( !cb.sc_private ) {
722                         /* If we didn't find an exact match, then try for <= */
723                         if ( findcsn_retry ) {
724                                 findcsn_retry = 0;
725                                 goto again;
726                         }
727                         rc = LDAP_NO_SUCH_OBJECT;
728                 }
729                 break;
730         case FIND_PRESENT:
731                 op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
732                 break;
733         }
734
735         return rc;
736 }
737
738 static void
739 syncprov_free_syncop( syncops *so )
740 {
741         syncres *sr, *srnext;
742         GroupAssertion *ga, *gnext;
743
744         ldap_pvt_thread_mutex_lock( &so->s_mutex );
745         if ( --so->s_inuse > 0 ) {
746                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
747                 return;
748         }
749         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
750         if ( so->s_flags & PS_IS_DETACHED ) {
751                 filter_free( so->s_op->ors_filter );
752                 for ( ga = so->s_op->o_groups; ga; ga=gnext ) {
753                         gnext = ga->ga_next;
754                         ch_free( ga );
755                 }
756                 ch_free( so->s_op );
757         }
758         ch_free( so->s_base.bv_val );
759         for ( sr=so->s_res; sr; sr=srnext ) {
760                 srnext = sr->s_next;
761                 ch_free( sr );
762         }
763         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
764         ch_free( so );
765 }
766
767 /* Send a persistent search response */
768 static int
769 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so,
770         Entry **e, int mode )
771 {
772         slap_overinst *on = opc->son;
773
774         SlapReply rs = { REP_SEARCH };
775         LDAPControl *ctrls[2];
776         struct berval cookie, csns[2];
777         Entry e_uuid = {0};
778         Attribute a_uuid = {0};
779
780         if ( so->s_op->o_abandon )
781                 return SLAPD_ABANDON;
782
783         ctrls[1] = NULL;
784         csns[0] = opc->sctxcsn;
785         BER_BVZERO( &csns[1] );
786         slap_compose_sync_cookie( op, &cookie, csns, so->s_rid, slap_serverID ? slap_serverID : -1 );
787
788 #ifdef LDAP_DEBUG
789         if ( so->s_sid > 0 ) {
790                 Debug( LDAP_DEBUG_SYNC, "syncprov_sendresp: to=%03x, cookie=%s\n",
791                         so->s_sid, cookie.bv_val, 0 );
792         } else {
793                 Debug( LDAP_DEBUG_SYNC, "syncprov_sendresp: cookie=%s\n",
794                         cookie.bv_val, 0, 0 );
795         }
796 #endif
797
798         e_uuid.e_attrs = &a_uuid;
799         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
800         a_uuid.a_nvals = &opc->suuid;
801         rs.sr_err = syncprov_state_ctrl( op, &rs, &e_uuid,
802                 mode, ctrls, 0, 1, &cookie );
803         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
804
805         rs.sr_ctrls = ctrls;
806         op->o_bd->bd_info = (BackendInfo *)on->on_info;
807         switch( mode ) {
808         case LDAP_SYNC_ADD:
809                 rs.sr_entry = *e;
810                 if ( rs.sr_entry->e_private )
811                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
812                 if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
813                         rs.sr_ref = get_entry_referrals( op, rs.sr_entry );
814                         rs.sr_err = send_search_reference( op, &rs );
815                         ber_bvarray_free( rs.sr_ref );
816                         if ( !rs.sr_entry )
817                                 *e = NULL;
818                         break;
819                 }
820                 /* fallthru */
821         case LDAP_SYNC_MODIFY:
822                 rs.sr_entry = *e;
823                 if ( rs.sr_entry->e_private )
824                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
825                 rs.sr_attrs = op->ors_attrs;
826                 rs.sr_err = send_search_entry( op, &rs );
827                 if ( !rs.sr_entry )
828                         *e = NULL;
829                 break;
830         case LDAP_SYNC_DELETE:
831                 e_uuid.e_attrs = NULL;
832                 e_uuid.e_name = opc->sdn;
833                 e_uuid.e_nname = opc->sndn;
834                 rs.sr_entry = &e_uuid;
835                 if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
836                         struct berval bv = BER_BVNULL;
837                         rs.sr_ref = &bv;
838                         rs.sr_err = send_search_reference( op, &rs );
839                 } else {
840                         rs.sr_err = send_search_entry( op, &rs );
841                 }
842                 break;
843         default:
844                 assert(0);
845         }
846         /* In case someone else freed it already? */
847         if ( rs.sr_ctrls ) {
848                 op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
849                 rs.sr_ctrls = NULL;
850         }
851
852         return rs.sr_err;
853 }
854
855 static void
856 syncprov_qstart( syncops *so );
857
858 /* Play back queued responses */
859 static int
860 syncprov_qplay( Operation *op, syncops *so )
861 {
862         slap_overinst *on = LDAP_SLIST_FIRST(&so->s_op->o_extra)->oe_key;
863         syncres *sr;
864         Entry *e;
865         opcookie opc;
866         int rc = 0;
867
868         opc.son = on;
869
870         do {
871                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
872                 sr = so->s_res;
873                 if ( sr )
874                         so->s_res = sr->s_next;
875                 if ( !so->s_res )
876                         so->s_restail = NULL;
877                 /* Exit loop with mutex held */
878                 if ( !sr || so->s_op->o_abandon )
879                         break;
880                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
881
882                 if ( sr->s_mode == LDAP_SYNC_NEW_COOKIE ) {
883                     SlapReply rs = { REP_INTERMEDIATE };
884
885                     rc = syncprov_sendinfo( op, &rs, LDAP_TAG_SYNC_NEW_COOKIE,
886                                 &sr->s_csn, 0, NULL, 0 );
887                 } else {
888                         opc.sdn = sr->s_dn;
889                         opc.sndn = sr->s_ndn;
890                         opc.suuid = sr->s_uuid;
891                         opc.sctxcsn = sr->s_csn;
892                         opc.sreference = sr->s_isreference;
893                         e = NULL;
894
895                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
896                                 rc = overlay_entry_get_ov( op, &opc.sndn, NULL, NULL, 0, &e, on );
897                                 if ( rc ) {
898                                         Debug( LDAP_DEBUG_SYNC, "syncprov_qplay: failed to get %s, "
899                                                 "error (%d), ignoring...\n", opc.sndn.bv_val, rc, 0 );
900                                         ch_free( sr );
901                                         rc = 0;
902                                         continue;
903                                 }
904                         }
905                         rc = syncprov_sendresp( op, &opc, so, &e, sr->s_mode );
906
907                         if ( e ) {
908                                 overlay_entry_release_ov( op, e, 0, on );
909                         }
910                 }
911
912                 ch_free( sr );
913
914                 /* Exit loop with mutex held */
915                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
916
917         } while (0);
918
919         /* We now only send one change at a time, to prevent one
920          * psearch from hogging all the CPU. Resubmit this task if
921          * there are more responses queued and no errors occurred.
922          */
923
924         if ( rc == 0 && so->s_res ) {
925                 syncprov_qstart( so );
926         } else {
927                 so->s_flags ^= PS_TASK_QUEUED;
928         }
929
930         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
931         return rc;
932 }
933
934 /* task for playing back queued responses */
935 static void *
936 syncprov_qtask( void *ctx, void *arg )
937 {
938         syncops *so = arg;
939         OperationBuffer opbuf;
940         Operation *op;
941         BackendDB be;
942         int rc;
943
944         op = &opbuf.ob_op;
945         *op = *so->s_op;
946         op->o_hdr = &opbuf.ob_hdr;
947         op->o_controls = opbuf.ob_controls;
948         memset( op->o_controls, 0, sizeof(opbuf.ob_controls) );
949
950         *op->o_hdr = *so->s_op->o_hdr;
951
952         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx, 1);
953         op->o_tmpmfuncs = &slap_sl_mfuncs;
954         op->o_threadctx = ctx;
955
956         /* syncprov_qplay expects a fake db */
957         be = *so->s_op->o_bd;
958         be.be_flags |= SLAP_DBFLAG_OVERLAY;
959         op->o_bd = &be;
960         LDAP_SLIST_FIRST(&op->o_extra) = NULL;
961         op->o_callback = NULL;
962
963         rc = syncprov_qplay( op, so );
964
965         /* decrement use count... */
966         syncprov_free_syncop( so );
967
968         return NULL;
969 }
970
971 /* Start the task to play back queued psearch responses */
972 static void
973 syncprov_qstart( syncops *so )
974 {
975         so->s_flags |= PS_TASK_QUEUED;
976         so->s_inuse++;
977         ldap_pvt_thread_pool_submit( &connection_pool, 
978                 syncprov_qtask, so );
979 }
980
981 /* Queue a persistent search response */
982 static int
983 syncprov_qresp( opcookie *opc, syncops *so, int mode )
984 {
985         syncres *sr;
986         int srsize;
987         struct berval cookie = opc->sctxcsn;
988
989         if ( mode == LDAP_SYNC_NEW_COOKIE ) {
990                 syncprov_info_t *si = opc->son->on_bi.bi_private;
991
992                 slap_compose_sync_cookie( NULL, &cookie, si->si_ctxcsn,
993                         so->s_rid, slap_serverID ? slap_serverID : -1);
994         }
995
996         srsize = sizeof(syncres) + opc->suuid.bv_len + 1 +
997                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1;
998         if ( cookie.bv_len )
999                 srsize += cookie.bv_len + 1;
1000         sr = ch_malloc( srsize );
1001         sr->s_next = NULL;
1002         sr->s_dn.bv_val = (char *)(sr + 1);
1003         sr->s_dn.bv_len = opc->sdn.bv_len;
1004         sr->s_mode = mode;
1005         sr->s_isreference = opc->sreference;
1006         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val,
1007                  opc->sdn.bv_val ) + 1;
1008         sr->s_ndn.bv_len = opc->sndn.bv_len;
1009         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val,
1010                  opc->sndn.bv_val ) + 1;
1011         sr->s_uuid.bv_len = opc->suuid.bv_len;
1012         AC_MEMCPY( sr->s_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1013         if ( cookie.bv_len ) {
1014                 sr->s_csn.bv_val = sr->s_uuid.bv_val + sr->s_uuid.bv_len + 1;
1015                 strcpy( sr->s_csn.bv_val, cookie.bv_val );
1016         } else {
1017                 sr->s_csn.bv_val = NULL;
1018         }
1019         sr->s_csn.bv_len = cookie.bv_len;
1020
1021         if ( mode == LDAP_SYNC_NEW_COOKIE && cookie.bv_val ) {
1022                 ch_free( cookie.bv_val );
1023         }
1024
1025         ldap_pvt_thread_mutex_lock( &so->s_mutex );
1026         if ( !so->s_res ) {
1027                 so->s_res = sr;
1028         } else {
1029                 so->s_restail->s_next = sr;
1030         }
1031         so->s_restail = sr;
1032
1033         /* If the base of the psearch was modified, check it next time round */
1034         if ( so->s_flags & PS_WROTE_BASE ) {
1035                 so->s_flags ^= PS_WROTE_BASE;
1036                 so->s_flags |= PS_FIND_BASE;
1037         }
1038         if (( so->s_flags & (PS_IS_DETACHED|PS_TASK_QUEUED)) == PS_IS_DETACHED ) {
1039                 syncprov_qstart( so );
1040         }
1041         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
1042         return LDAP_SUCCESS;
1043 }
1044
1045 static int
1046 syncprov_drop_psearch( syncops *so, int lock )
1047 {
1048         if ( so->s_flags & PS_IS_DETACHED ) {
1049                 if ( lock )
1050                         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
1051                 so->s_op->o_conn->c_n_ops_executing--;
1052                 so->s_op->o_conn->c_n_ops_completed++;
1053                 LDAP_STAILQ_REMOVE( &so->s_op->o_conn->c_ops, so->s_op, Operation,
1054                         o_next );
1055                 if ( lock )
1056                         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
1057         }
1058         syncprov_free_syncop( so );
1059
1060         return 0;
1061 }
1062
1063 static int
1064 syncprov_ab_cleanup( Operation *op, SlapReply *rs )
1065 {
1066         slap_callback *sc = op->o_callback;
1067         op->o_callback = sc->sc_next;
1068         syncprov_drop_psearch( op->o_callback->sc_private, 0 );
1069         op->o_tmpfree( sc, op->o_tmpmemctx );
1070         return 0;
1071 }
1072
1073 static int
1074 syncprov_op_abandon( Operation *op, SlapReply *rs )
1075 {
1076         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1077         syncprov_info_t         *si = on->on_bi.bi_private;
1078         syncops *so, *soprev;
1079
1080         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1081         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
1082                 soprev=so, so=so->s_next ) {
1083                 if ( so->s_op->o_connid == op->o_connid &&
1084                         so->s_op->o_msgid == op->orn_msgid ) {
1085                                 so->s_op->o_abandon = 1;
1086                                 soprev->s_next = so->s_next;
1087                                 break;
1088                 }
1089         }
1090         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1091         if ( so ) {
1092                 /* Is this really a Cancel exop? */
1093                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
1094                         so->s_op->o_cancel = SLAP_CANCEL_ACK;
1095                         rs->sr_err = LDAP_CANCELLED;
1096                         send_ldap_result( so->s_op, rs );
1097                         if ( so->s_flags & PS_IS_DETACHED ) {
1098                                 slap_callback *cb;
1099                                 cb = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1100                                 cb->sc_cleanup = syncprov_ab_cleanup;
1101                                 cb->sc_next = op->o_callback;
1102                                 cb->sc_private = so;
1103                                 return SLAP_CB_CONTINUE;
1104                         }
1105                 }
1106                 syncprov_drop_psearch( so, 0 );
1107         }
1108         return SLAP_CB_CONTINUE;
1109 }
1110
1111 /* Find which persistent searches are affected by this operation */
1112 static void
1113 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
1114 {
1115         slap_overinst *on = opc->son;
1116         syncprov_info_t         *si = on->on_bi.bi_private;
1117
1118         fbase_cookie fc;
1119         syncops *ss, *sprev, *snext;
1120         struct sync_cookie *scook;
1121         Entry *e = NULL;
1122         Attribute *a;
1123         int rc;
1124         struct berval newdn;
1125         int freefdn = 0;
1126         BackendDB *b0 = op->o_bd, db;
1127
1128         fc.fdn = &op->o_req_ndn;
1129         /* compute new DN */
1130         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1131                 struct berval pdn;
1132                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
1133                 else dnParent( fc.fdn, &pdn );
1134                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
1135                 fc.fdn = &newdn;
1136                 freefdn = 1;
1137         }
1138         if ( op->o_tag != LDAP_REQ_ADD ) {
1139                 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1140                         db = *op->o_bd;
1141                         op->o_bd = &db;
1142                 }
1143                 rc = overlay_entry_get_ov( op, fc.fdn, NULL, NULL, 0, &e, on );
1144                 /* If we're sending responses now, make a copy and unlock the DB */
1145                 if ( e && !saveit ) {
1146                         Entry *e2 = entry_dup( e );
1147                         overlay_entry_release_ov( op, e, 0, on );
1148                         e = e2;
1149                 }
1150                 if ( rc ) {
1151                         op->o_bd = b0;
1152                         return;
1153                 }
1154         } else {
1155                 e = op->ora_e;
1156         }
1157
1158         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
1159                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1160                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1161                 opc->sreference = is_entry_referral( e );
1162                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
1163                 if ( a )
1164                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
1165         } else if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1166                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1167                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1168                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1169                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1170         }
1171
1172         scook = op->o_controls ? op->o_controls[slap_cids.sc_LDAPsync] : NULL;
1173         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1174         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
1175                 sprev = ss, ss=snext)
1176         {
1177                 Operation op2;
1178                 Opheader oh;
1179                 syncmatches *sm;
1180                 int found = 0;
1181
1182                 snext = ss->s_next;
1183                 if ( ss->s_op->o_abandon )
1184                         continue;
1185
1186                 /* First time thru, check for possible skips */
1187                 if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
1188
1189                         /* Don't send ops back to the originator */
1190                         if ( opc->ssid > 0 && opc->ssid == ss->s_sid ) {
1191                                 Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping original sid %03x\n",
1192                                         opc->ssid, 0, 0 );
1193                                 continue;
1194                         }
1195
1196                         /* Don't send ops back to the messenger */
1197                         if ( scook && scook->sid > 0 && scook->sid == ss->s_sid ) {
1198                                 Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping relayed sid %03x\n",
1199                                         scook->sid, 0, 0 );
1200                                 continue;
1201                         }
1202                 }
1203
1204                 /* validate base */
1205                 fc.fss = ss;
1206                 fc.fbase = 0;
1207                 fc.fscope = 0;
1208
1209                 /* If the base of the search is missing, signal a refresh */
1210                 rc = syncprov_findbase( op, &fc );
1211                 if ( rc != LDAP_SUCCESS ) {
1212                         SlapReply rs = {REP_RESULT};
1213                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
1214                                 "search base has changed" );
1215                         sprev->s_next = snext;
1216                         syncprov_drop_psearch( ss, 1 );
1217                         ss = sprev;
1218                         continue;
1219                 }
1220
1221
1222                 /* If we're sending results now, look for this op in old matches */
1223                 if ( !saveit ) {
1224                         syncmatches *old;
1225
1226                         /* Did we modify the search base? */
1227                         if ( dn_match( &op->o_req_ndn, &ss->s_base )) {
1228                                 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1229                                 ss->s_flags |= PS_WROTE_BASE;
1230                                 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1231                         }
1232
1233                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
1234                                 old=sm, sm=sm->sm_next ) {
1235                                 if ( sm->sm_op == ss ) {
1236                                         found = 1;
1237                                         old->sm_next = sm->sm_next;
1238                                         op->o_tmpfree( sm, op->o_tmpmemctx );
1239                                         break;
1240                                 }
1241                         }
1242                 }
1243
1244                 if ( fc.fscope ) {
1245                         op2 = *ss->s_op;
1246                         oh = *op->o_hdr;
1247                         oh.oh_conn = ss->s_op->o_conn;
1248                         oh.oh_connid = ss->s_op->o_connid;
1249                         op2.o_hdr = &oh;
1250                         op2.o_extra = op->o_extra;
1251                         rc = test_filter( &op2, e, ss->s_op->ors_filter );
1252                 }
1253
1254                 Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: sid %03x fscope %d rc %d\n",
1255                         ss->s_sid, fc.fscope, rc );
1256
1257                 /* check if current o_req_dn is in scope and matches filter */
1258                 if ( fc.fscope && rc == LDAP_COMPARE_TRUE ) {
1259                         if ( saveit ) {
1260                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
1261                                 sm->sm_next = opc->smatches;
1262                                 sm->sm_op = ss;
1263                                 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1264                                 ++ss->s_inuse;
1265                                 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1266                                 opc->smatches = sm;
1267                         } else {
1268                                 /* if found send UPDATE else send ADD */
1269                                 syncprov_qresp( opc, ss,
1270                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD );
1271                         }
1272                 } else if ( !saveit && found ) {
1273                         /* send DELETE */
1274                         syncprov_qresp( opc, ss, LDAP_SYNC_DELETE );
1275                 } else if ( !saveit ) {
1276                         syncprov_qresp( opc, ss, LDAP_SYNC_NEW_COOKIE );
1277                 }
1278                 if ( !saveit && found ) {
1279                         /* Decrement s_inuse, was incremented when called
1280                          * with saveit == TRUE
1281                          */
1282                         syncprov_free_syncop( ss );
1283                 }
1284         }
1285         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1286
1287         if ( op->o_tag != LDAP_REQ_ADD && e ) {
1288                 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1289                         op->o_bd = &db;
1290                 }
1291                 overlay_entry_release_ov( op, e, 0, on );
1292                 op->o_bd = b0;
1293         }
1294         if ( freefdn ) {
1295                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
1296         }
1297         op->o_bd = b0;
1298 }
1299
1300 static int
1301 syncprov_op_cleanup( Operation *op, SlapReply *rs )
1302 {
1303         slap_callback *cb = op->o_callback;
1304         opcookie *opc = cb->sc_private;
1305         slap_overinst *on = opc->son;
1306         syncprov_info_t         *si = on->on_bi.bi_private;
1307         syncmatches *sm, *snext;
1308         modtarget *mt, mtdummy;
1309
1310         for (sm = opc->smatches; sm; sm=snext) {
1311                 snext = sm->sm_next;
1312                 syncprov_free_syncop( sm->sm_op );
1313                 op->o_tmpfree( sm, op->o_tmpmemctx );
1314         }
1315
1316         /* Remove op from lock table */
1317         mtdummy.mt_op = op;
1318         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1319         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1320         if ( mt ) {
1321                 modinst *mi = mt->mt_mods;
1322
1323                 /* If there are more, promote the next one */
1324                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1325                 if ( mi->mi_next ) {
1326                         mt->mt_mods = mi->mi_next;
1327                         mt->mt_op = mt->mt_mods->mi_op;
1328                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1329                 } else {
1330                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
1331                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1332                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1333                         ch_free( mt );
1334                 }
1335         }
1336         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1337         if ( !BER_BVISNULL( &opc->suuid ))
1338                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1339         if ( !BER_BVISNULL( &opc->sndn ))
1340                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1341         if ( !BER_BVISNULL( &opc->sdn ))
1342                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1343         op->o_callback = cb->sc_next;
1344         op->o_tmpfree(cb, op->o_tmpmemctx);
1345
1346         return 0;
1347 }
1348
1349 static void
1350 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1351 {
1352         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1353         Modifications mod;
1354         Operation opm;
1355         SlapReply rsm = { 0 };
1356         slap_callback cb = {0};
1357         BackendDB be;
1358 #ifdef CHECK_CSN
1359         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
1360
1361         int i;
1362         for ( i=0; i<si->si_numcsns; i++ ) {
1363                 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1364         }
1365 #endif
1366         mod.sml_numvals = si->si_numcsns;
1367         mod.sml_values = si->si_ctxcsn;
1368         mod.sml_nvalues = NULL;
1369         mod.sml_desc = slap_schema.si_ad_contextCSN;
1370         mod.sml_op = LDAP_MOD_REPLACE;
1371         mod.sml_flags = SLAP_MOD_INTERNAL;
1372         mod.sml_next = NULL;
1373
1374         cb.sc_response = slap_null_cb;
1375         opm = *op;
1376         opm.o_tag = LDAP_REQ_MODIFY;
1377         opm.o_callback = &cb;
1378         opm.orm_modlist = &mod;
1379         opm.orm_no_opattrs = 1;
1380         if ( SLAP_GLUE_SUBORDINATE( op->o_bd )) {
1381                 be = *on->on_info->oi_origdb;
1382                 opm.o_bd = &be;
1383         }
1384         opm.o_req_dn = opm.o_bd->be_suffix[0];
1385         opm.o_req_ndn = opm.o_bd->be_nsuffix[0];
1386         opm.o_bd->bd_info = on->on_info->oi_orig;
1387         opm.o_managedsait = SLAP_CONTROL_NONCRITICAL;
1388         opm.o_no_schema_check = 1;
1389         opm.o_bd->be_modify( &opm, &rsm );
1390         if ( mod.sml_next != NULL ) {
1391                 slap_mods_free( mod.sml_next, 1 );
1392         }
1393 #ifdef CHECK_CSN
1394         for ( i=0; i<si->si_numcsns; i++ ) {
1395                 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1396         }
1397 #endif
1398 }
1399
1400 static void
1401 syncprov_add_slog( Operation *op )
1402 {
1403         opcookie *opc = op->o_callback->sc_private;
1404         slap_overinst *on = opc->son;
1405         syncprov_info_t         *si = on->on_bi.bi_private;
1406         sessionlog *sl;
1407         slog_entry *se;
1408
1409         sl = si->si_logs;
1410         {
1411                 /* Allocate a record. UUIDs are not NUL-terminated. */
1412                 se = ch_malloc( sizeof( slog_entry ) + opc->suuid.bv_len + 
1413                         op->o_csn.bv_len + 1 );
1414                 se->se_next = NULL;
1415                 se->se_tag = op->o_tag;
1416
1417                 se->se_uuid.bv_val = (char *)(&se[1]);
1418                 AC_MEMCPY( se->se_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1419                 se->se_uuid.bv_len = opc->suuid.bv_len;
1420
1421                 se->se_csn.bv_val = se->se_uuid.bv_val + opc->suuid.bv_len;
1422                 AC_MEMCPY( se->se_csn.bv_val, op->o_csn.bv_val, op->o_csn.bv_len );
1423                 se->se_csn.bv_val[op->o_csn.bv_len] = '\0';
1424                 se->se_csn.bv_len = op->o_csn.bv_len;
1425                 se->se_sid = slap_parse_csn_sid( &se->se_csn );
1426
1427                 ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
1428                 if ( sl->sl_head ) {
1429                         sl->sl_tail->se_next = se;
1430                 } else {
1431                         sl->sl_head = se;
1432                 }
1433                 sl->sl_tail = se;
1434                 sl->sl_num++;
1435                 while ( sl->sl_num > sl->sl_size ) {
1436                         se = sl->sl_head;
1437                         sl->sl_head = se->se_next;
1438                         strcpy( sl->sl_mincsn.bv_val, se->se_csn.bv_val );
1439                         sl->sl_mincsn.bv_len = se->se_csn.bv_len;
1440                         ch_free( se );
1441                         sl->sl_num--;
1442                 }
1443                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1444         }
1445 }
1446
1447 /* Just set a flag if we found the matching entry */
1448 static int
1449 playlog_cb( Operation *op, SlapReply *rs )
1450 {
1451         if ( rs->sr_type == REP_SEARCH ) {
1452                 op->o_callback->sc_private = (void *)1;
1453         }
1454         return rs->sr_err;
1455 }
1456
1457 /* enter with sl->sl_mutex locked, release before returning */
1458 static void
1459 syncprov_playlog( Operation *op, SlapReply *rs, sessionlog *sl,
1460         sync_control *srs, BerVarray ctxcsn, int numcsns, int *sids )
1461 {
1462         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1463         slog_entry *se;
1464         int i, j, ndel, num, nmods, mmods;
1465         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1466         BerVarray uuids;
1467         struct berval delcsn[2];
1468
1469         if ( !sl->sl_num ) {
1470                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1471                 return;
1472         }
1473
1474         num = sl->sl_num;
1475         i = 0;
1476         nmods = 0;
1477
1478         uuids = op->o_tmpalloc( (num+1) * sizeof( struct berval ) +
1479                 num * UUID_LEN, op->o_tmpmemctx );
1480         uuids[0].bv_val = (char *)(uuids + num + 1);
1481
1482         delcsn[0].bv_len = 0;
1483         delcsn[0].bv_val = cbuf;
1484         BER_BVZERO(&delcsn[1]);
1485
1486         /* Make a copy of the relevant UUIDs. Put the Deletes up front
1487          * and everything else at the end. Do this first so we can
1488          * unlock the list mutex.
1489          */
1490         Debug( LDAP_DEBUG_SYNC, "srs csn %s\n",
1491                 srs->sr_state.ctxcsn[0].bv_val, 0, 0 );
1492         for ( se=sl->sl_head; se; se=se->se_next ) {
1493                 int k;
1494                 Debug( LDAP_DEBUG_SYNC, "log csn %s\n", se->se_csn.bv_val, 0, 0 );
1495                 ndel = 1;
1496                 for ( k=0; k<srs->sr_state.numcsns; k++ ) {
1497                         if ( se->se_sid == srs->sr_state.sids[k] ) {
1498                                 ndel = ber_bvcmp( &se->se_csn, &srs->sr_state.ctxcsn[k] );
1499                                 break;
1500                         }
1501                 }
1502                 if ( ndel <= 0 ) {
1503                         Debug( LDAP_DEBUG_SYNC, "cmp %d, too old\n", ndel, 0, 0 );
1504                         continue;
1505                 }
1506                 ndel = 0;
1507                 for ( k=0; k<numcsns; k++ ) {
1508                         if ( se->se_sid == sids[k] ) {
1509                                 ndel = ber_bvcmp( &se->se_csn, &ctxcsn[k] );
1510                                 break;
1511                         }
1512                 }
1513                 if ( ndel > 0 ) {
1514                         Debug( LDAP_DEBUG_SYNC, "cmp %d, too new\n", ndel, 0, 0 );
1515                         break;
1516                 }
1517                 if ( se->se_tag == LDAP_REQ_DELETE ) {
1518                         j = i;
1519                         i++;
1520                         AC_MEMCPY( cbuf, se->se_csn.bv_val, se->se_csn.bv_len );
1521                         delcsn[0].bv_len = se->se_csn.bv_len;
1522                         delcsn[0].bv_val[delcsn[0].bv_len] = '\0';
1523                 } else {
1524                         nmods++;
1525                         j = num - nmods;
1526                 }
1527                 uuids[j].bv_val = uuids[0].bv_val + (j * UUID_LEN);
1528                 AC_MEMCPY(uuids[j].bv_val, se->se_uuid.bv_val, UUID_LEN);
1529                 uuids[j].bv_len = UUID_LEN;
1530         }
1531         ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1532
1533         ndel = i;
1534
1535         /* Zero out unused slots */
1536         for ( i=ndel; i < num - nmods; i++ )
1537                 uuids[i].bv_len = 0;
1538
1539         /* Mods must be validated to see if they belong in this delete set.
1540          */
1541
1542         mmods = nmods;
1543         /* Strip any duplicates */
1544         for ( i=0; i<nmods; i++ ) {
1545                 for ( j=0; j<ndel; j++ ) {
1546                         if ( bvmatch( &uuids[j], &uuids[num - 1 - i] )) {
1547                                 uuids[num - 1 - i].bv_len = 0;
1548                                 mmods --;
1549                                 break;
1550                         }
1551                 }
1552                 if ( uuids[num - 1 - i].bv_len == 0 ) continue;
1553                 for ( j=0; j<i; j++ ) {
1554                         if ( bvmatch( &uuids[num - 1 - j], &uuids[num - 1 - i] )) {
1555                                 uuids[num - 1 - i].bv_len = 0;
1556                                 mmods --;
1557                                 break;
1558                         }
1559                 }
1560         }
1561
1562         if ( mmods ) {
1563                 Operation fop;
1564                 SlapReply frs = { REP_RESULT };
1565                 int rc;
1566                 Filter mf, af;
1567                 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
1568                 slap_callback cb = {0};
1569
1570                 fop = *op;
1571
1572                 fop.o_sync_mode = 0;
1573                 fop.o_callback = &cb;
1574                 fop.ors_limit = NULL;
1575                 fop.ors_tlimit = SLAP_NO_LIMIT;
1576                 fop.ors_attrs = slap_anlist_all_attributes;
1577                 fop.ors_attrsonly = 0;
1578                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
1579
1580                 af.f_choice = LDAP_FILTER_AND;
1581                 af.f_next = NULL;
1582                 af.f_and = &mf;
1583                 mf.f_choice = LDAP_FILTER_EQUALITY;
1584                 mf.f_ava = &eq;
1585                 mf.f_av_desc = slap_schema.si_ad_entryUUID;
1586                 mf.f_next = fop.ors_filter;
1587
1588                 fop.ors_filter = &af;
1589
1590                 cb.sc_response = playlog_cb;
1591                 fop.o_bd->bd_info = (BackendInfo *)on->on_info;
1592
1593                 for ( i=ndel; i<num; i++ ) {
1594                         if ( uuids[i].bv_len == 0 ) continue;
1595
1596                         mf.f_av_value = uuids[i];
1597                         cb.sc_private = NULL;
1598                         fop.ors_slimit = 1;
1599                         frs.sr_nentries = 0;
1600                         rc = fop.o_bd->be_search( &fop, &frs );
1601
1602                         /* If entry was not found, add to delete list */
1603                         if ( !cb.sc_private ) {
1604                                 uuids[ndel++] = uuids[i];
1605                         }
1606                 }
1607                 fop.o_bd->bd_info = (BackendInfo *)on;
1608         }
1609         if ( ndel ) {
1610                 struct berval cookie;
1611
1612                 if ( delcsn[0].bv_len ) {
1613                         slap_compose_sync_cookie( op, &cookie, delcsn, srs->sr_state.rid,
1614                                 slap_serverID ? slap_serverID : -1 );
1615
1616                         Debug( LDAP_DEBUG_SYNC, "syncprov_playlog: cookie=%s\n", cookie.bv_val, 0, 0 );
1617                 }
1618
1619                 uuids[ndel].bv_val = NULL;
1620                 syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET,
1621                         delcsn[0].bv_len ? &cookie : NULL, 0, uuids, 1 );
1622                 if ( delcsn[0].bv_len ) {
1623                         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
1624                 }
1625         }
1626         op->o_tmpfree( uuids, op->o_tmpmemctx );
1627 }
1628
1629 static int
1630 syncprov_op_response( Operation *op, SlapReply *rs )
1631 {
1632         opcookie *opc = op->o_callback->sc_private;
1633         slap_overinst *on = opc->son;
1634         syncprov_info_t         *si = on->on_bi.bi_private;
1635         syncmatches *sm;
1636
1637         if ( rs->sr_err == LDAP_SUCCESS )
1638         {
1639                 struct berval maxcsn;
1640                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1641                 int do_check = 0, have_psearches, foundit, csn_changed = 0;
1642
1643                 /* Update our context CSN */
1644                 cbuf[0] = '\0';
1645                 maxcsn.bv_val = cbuf;
1646                 maxcsn.bv_len = sizeof(cbuf);
1647                 ldap_pvt_thread_rdwr_wlock( &si->si_csn_rwlock );
1648
1649 #if 0
1650                 if ( op->o_dont_replicate &&
1651                                 op->orm_modlist->sml_op == LDAP_MOD_REPLACE &&
1652                                 op->orm_modlist->sml_desc == slap_schema.si_ad_contextCSN ) {
1653                         /* Catch contextCSN updates from syncrepl. We have to look at
1654                          * all the attribute values, as there may be more than one csn
1655                          * that changed, and only one can be passed in the csn queue.
1656                          */
1657                         Modifications *mod = op->orm_modlist;
1658                         int i, j, sid;
1659
1660                         for ( i=0; i<mod->sml_numvals; i++ ) {
1661                                 sid = slap_parse_csn_sid( &mod->sml_values[i] );
1662
1663                                 for ( j=0; j<si->si_numcsns; j++ ) {
1664                                         if ( sid == si->si_sids[j] ) {
1665                                                 if ( ber_bvcmp( &mod->sml_values[i], &si->si_ctxcsn[j] ) > 0 ) {
1666                                                         ber_bvreplace( &si->si_ctxcsn[j], &mod->sml_values[i] );
1667                                                         csn_changed = 1;
1668                                                 }
1669                                                 break;
1670                                         }
1671                                 }
1672
1673                                 if ( j == si->si_numcsns ) {
1674                                         value_add_one( &si->si_ctxcsn, &mod->sml_values[i] );
1675                                         si->si_numcsns++;
1676                                         si->si_sids = ch_realloc( si->si_sids, si->si_numcsns *
1677                                                 sizeof(int));
1678                                         si->si_sids[j] = sid;
1679                                         csn_changed = 1;
1680                                 }
1681                         }
1682                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1683
1684                         if ( csn_changed ) {
1685                                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1686                                 have_psearches = ( si->si_ops != NULL );
1687                                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1688
1689                                 if ( have_psearches ) {
1690                                         for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1691                                                 if ( sm->sm_op->s_op->o_abandon )
1692                                                         continue;
1693                                                 syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_NEW_COOKIE );
1694                                         }
1695                                 }
1696                         }
1697                         return SLAP_CB_CONTINUE;
1698                 }
1699 #endif
1700
1701                 slap_get_commit_csn( op, &maxcsn, &foundit );
1702                 if ( BER_BVISEMPTY( &maxcsn ) && SLAP_GLUE_SUBORDINATE( op->o_bd )) {
1703                         /* syncrepl queues the CSN values in the db where
1704                          * it is configured , not where the changes are made.
1705                          * So look for a value in the glue db if we didn't
1706                          * find any in this db.
1707                          */
1708                         BackendDB *be = op->o_bd;
1709                         op->o_bd = select_backend( &be->be_nsuffix[0], 1);
1710                         maxcsn.bv_val = cbuf;
1711                         maxcsn.bv_len = sizeof(cbuf);
1712                         slap_get_commit_csn( op, &maxcsn, &foundit );
1713                         op->o_bd = be;
1714                 }
1715                 if ( !BER_BVISEMPTY( &maxcsn ) ) {
1716                         int i, sid;
1717 #ifdef CHECK_CSN
1718                         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
1719                         assert( !syn->ssyn_validate( syn, &maxcsn ));
1720 #endif
1721                         sid = slap_parse_csn_sid( &maxcsn );
1722                         for ( i=0; i<si->si_numcsns; i++ ) {
1723                                 if ( sid == si->si_sids[i] ) {
1724                                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn[i] ) > 0 ) {
1725                                                 ber_bvreplace( &si->si_ctxcsn[i], &maxcsn );
1726                                                 csn_changed = 1;
1727                                         }
1728                                         break;
1729                                 }
1730                         }
1731                         /* It's a new SID for us */
1732                         if ( i == si->si_numcsns ) {
1733                                 value_add_one( &si->si_ctxcsn, &maxcsn );
1734                                 csn_changed = 1;
1735                                 si->si_numcsns++;
1736                                 si->si_sids = ch_realloc( si->si_sids, si->si_numcsns *
1737                                         sizeof(int));
1738                                 si->si_sids[i] = sid;
1739                         }
1740                 } else if ( !foundit ) {
1741                         /* internal ops that aren't meant to be replicated */
1742                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1743                         return SLAP_CB_CONTINUE;
1744                 }
1745
1746                 /* Don't do any processing for consumer contextCSN updates */
1747                 if ( op->o_dont_replicate ) {
1748                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1749                         return SLAP_CB_CONTINUE;
1750                 }
1751
1752                 si->si_numops++;
1753                 if ( si->si_chkops || si->si_chktime ) {
1754                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1755                                 do_check = 1;
1756                                 si->si_numops = 0;
1757                         }
1758                         if ( si->si_chktime &&
1759                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1760                                 if ( si->si_chklast ) {
1761                                         do_check = 1;
1762                                         si->si_chklast = op->o_time;
1763                                 } else {
1764                                         si->si_chklast = 1;
1765                                 }
1766                         }
1767                 }
1768                 ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1769
1770                 if ( do_check ) {
1771                         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
1772                         syncprov_checkpoint( op, rs, on );
1773                         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
1774                 }
1775
1776                 /* only update consumer ctx if this is a newer csn */
1777                 if ( csn_changed ) {
1778                         opc->sctxcsn = maxcsn;
1779                 }
1780
1781                 /* Handle any persistent searches */
1782                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1783                 have_psearches = ( si->si_ops != NULL );
1784                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1785                 if ( have_psearches ) {
1786                         switch(op->o_tag) {
1787                         case LDAP_REQ_ADD:
1788                         case LDAP_REQ_MODIFY:
1789                         case LDAP_REQ_MODRDN:
1790                         case LDAP_REQ_EXTENDED:
1791                                 syncprov_matchops( op, opc, 0 );
1792                                 break;
1793                         case LDAP_REQ_DELETE:
1794                                 /* for each match in opc->smatches:
1795                                  *   send DELETE msg
1796                                  */
1797                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1798                                         if ( sm->sm_op->s_op->o_abandon )
1799                                                 continue;
1800                                         syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_DELETE );
1801                                 }
1802                                 break;
1803                         }
1804                 }
1805
1806                 /* Add any log records */
1807                 if ( si->si_logs && op->o_tag != LDAP_REQ_ADD ) {
1808                         syncprov_add_slog( op );
1809                 }
1810
1811         }
1812         return SLAP_CB_CONTINUE;
1813 }
1814
1815 /* We don't use a subentry to store the context CSN any more.
1816  * We expose the current context CSN as an operational attribute
1817  * of the suffix entry.
1818  */
1819 static int
1820 syncprov_op_compare( Operation *op, SlapReply *rs )
1821 {
1822         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1823         syncprov_info_t         *si = on->on_bi.bi_private;
1824         int rc = SLAP_CB_CONTINUE;
1825
1826         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1827                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1828         {
1829                 Entry e = {0};
1830                 Attribute a = {0};
1831
1832                 e.e_name = op->o_bd->be_suffix[0];
1833                 e.e_nname = op->o_bd->be_nsuffix[0];
1834                 e.e_attrs = &a;
1835
1836                 a.a_desc = slap_schema.si_ad_contextCSN;
1837
1838                 ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
1839
1840                 a.a_vals = si->si_ctxcsn;
1841                 a.a_nvals = a.a_vals;
1842                 a.a_numvals = si->si_numcsns;
1843
1844                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1845                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1846                 if ( ! rs->sr_err ) {
1847                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1848                         goto return_results;
1849                 }
1850
1851                 if ( get_assert( op ) &&
1852                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1853                 {
1854                         rs->sr_err = LDAP_ASSERTION_FAILED;
1855                         goto return_results;
1856                 }
1857
1858
1859                 rs->sr_err = LDAP_COMPARE_FALSE;
1860
1861                 if ( attr_valfind( &a,
1862                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1863                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1864                                 &op->oq_compare.rs_ava->aa_value, NULL, op->o_tmpmemctx ) == 0 )
1865                 {
1866                         rs->sr_err = LDAP_COMPARE_TRUE;
1867                 }
1868
1869 return_results:;
1870
1871                 ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
1872
1873                 send_ldap_result( op, rs );
1874
1875                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1876                         rs->sr_err = LDAP_SUCCESS;
1877                 }
1878                 rc = rs->sr_err;
1879         }
1880
1881         return rc;
1882 }
1883
1884 static int
1885 syncprov_op_mod( Operation *op, SlapReply *rs )
1886 {
1887         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1888         syncprov_info_t         *si = on->on_bi.bi_private;
1889         slap_callback *cb;
1890         opcookie *opc;
1891         int have_psearches, cbsize;
1892
1893         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1894         have_psearches = ( si->si_ops != NULL );
1895         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1896
1897         cbsize = sizeof(slap_callback) + sizeof(opcookie) +
1898                 (have_psearches ? sizeof(modinst) : 0 );
1899
1900         cb = op->o_tmpcalloc(1, cbsize, op->o_tmpmemctx);
1901         opc = (opcookie *)(cb+1);
1902         opc->son = on;
1903         cb->sc_response = syncprov_op_response;
1904         cb->sc_cleanup = syncprov_op_cleanup;
1905         cb->sc_private = opc;
1906         cb->sc_next = op->o_callback;
1907         op->o_callback = cb;
1908
1909         if ( op->o_csn.bv_val ) {
1910                 opc->ssid = slap_parse_csn_sid( &op->o_csn );
1911         } else {
1912                 opc->ssid = -1;
1913         }
1914
1915         /* If there are active persistent searches, lock this operation.
1916          * See seqmod.c for the locking logic on its own.
1917          */
1918         if ( have_psearches ) {
1919                 modtarget *mt, mtdummy;
1920                 modinst *mi;
1921
1922                 mi = (modinst *)(opc+1);
1923                 mi->mi_op = op;
1924
1925                 /* See if we're already modifying this entry... */
1926                 mtdummy.mt_op = op;
1927                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1928                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1929                 if ( mt ) {
1930                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1931                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1932                         mt->mt_tail->mi_next = mi;
1933                         mt->mt_tail = mi;
1934                         /* wait for this op to get to head of list */
1935                         while ( mt->mt_mods != mi ) {
1936                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1937                                 /* FIXME: if dynamic config can delete overlays or
1938                                  * databases we'll have to check for cleanup here.
1939                                  * Currently it's not an issue because there are
1940                                  * no dynamic config deletes...
1941                                  */
1942                                 if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1943                                         ldap_pvt_thread_yield();
1944                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1945
1946                                 /* clean up if the caller is giving up */
1947                                 if ( op->o_abandon ) {
1948                                         modinst *m2;
1949                                         for ( m2 = mt->mt_mods; m2->mi_next != mi;
1950                                                 m2 = m2->mi_next );
1951                                         m2->mi_next = mi->mi_next;
1952                                         if ( mt->mt_tail == mi ) mt->mt_tail = m2;
1953                                         op->o_tmpfree( cb, op->o_tmpmemctx );
1954                                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1955                                         return SLAPD_ABANDON;
1956                                 }
1957                         }
1958                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1959                 } else {
1960                         /* Record that we're modifying this entry now */
1961                         mt = ch_malloc( sizeof(modtarget) );
1962                         mt->mt_mods = mi;
1963                         mt->mt_tail = mi;
1964                         mt->mt_op = mi->mi_op;
1965                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1966                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1967                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1968                 }
1969         }
1970
1971         if (( have_psearches || si->si_logs ) && op->o_tag != LDAP_REQ_ADD )
1972                 syncprov_matchops( op, opc, 1 );
1973
1974         return SLAP_CB_CONTINUE;
1975 }
1976
1977 static int
1978 syncprov_op_extended( Operation *op, SlapReply *rs )
1979 {
1980         if ( exop_is_write( op ))
1981                 return syncprov_op_mod( op, rs );
1982
1983         return SLAP_CB_CONTINUE;
1984 }
1985
1986 typedef struct searchstate {
1987         slap_overinst *ss_on;
1988         syncops *ss_so;
1989         BerVarray ss_ctxcsn;
1990         int *ss_sids;
1991         int ss_numcsns;
1992 #define SS_PRESENT      0x01
1993 #define SS_CHANGED      0x02
1994         int ss_flags;
1995 } searchstate;
1996
1997 static int
1998 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1999 {
2000         if ( rs->sr_ctrls ) {
2001                 op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
2002                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
2003                 rs->sr_ctrls = NULL;
2004         }
2005         return 0;
2006 }
2007
2008 typedef struct SyncOperationBuffer {
2009         Operation               sob_op;
2010         Opheader                sob_hdr;
2011         OpExtra                 sob_oe;
2012         AttributeName   sob_extra;      /* not always present */
2013         /* Further data allocated here */
2014 } SyncOperationBuffer;
2015
2016 static void
2017 syncprov_detach_op( Operation *op, syncops *so, slap_overinst *on )
2018 {
2019         SyncOperationBuffer *sopbuf2;
2020         Operation *op2;
2021         int i, alen = 0;
2022         size_t size;
2023         char *ptr;
2024         GroupAssertion *g1, *g2;
2025
2026         /* count the search attrs */
2027         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2028                 alen += op->ors_attrs[i].an_name.bv_len + 1;
2029         }
2030         /* Make a new copy of the operation */
2031         size = offsetof( SyncOperationBuffer, sob_extra ) +
2032                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
2033                 op->o_req_dn.bv_len + 1 +
2034                 op->o_req_ndn.bv_len + 1 +
2035                 op->o_ndn.bv_len + 1 +
2036                 so->s_filterstr.bv_len + 1;
2037         sopbuf2 = ch_calloc( 1, size );
2038         op2 = &sopbuf2->sob_op;
2039         op2->o_hdr = &sopbuf2->sob_hdr;
2040         LDAP_SLIST_FIRST(&op2->o_extra) = &sopbuf2->sob_oe;
2041
2042         /* Copy the fields we care about explicitly, leave the rest alone */
2043         *op2->o_hdr = *op->o_hdr;
2044         op2->o_tag = op->o_tag;
2045         op2->o_time = op->o_time;
2046         op2->o_bd = on->on_info->oi_origdb;
2047         op2->o_request = op->o_request;
2048         op2->o_managedsait = op->o_managedsait;
2049         LDAP_SLIST_FIRST(&op2->o_extra)->oe_key = on;
2050         LDAP_SLIST_NEXT(LDAP_SLIST_FIRST(&op2->o_extra), oe_next) = NULL;
2051
2052         ptr = (char *) sopbuf2 + offsetof( SyncOperationBuffer, sob_extra );
2053         if ( i ) {
2054                 op2->ors_attrs = (AttributeName *) ptr;
2055                 ptr = (char *) &op2->ors_attrs[i+1];
2056                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2057                         op2->ors_attrs[i] = op->ors_attrs[i];
2058                         op2->ors_attrs[i].an_name.bv_val = ptr;
2059                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
2060                 }
2061                 BER_BVZERO( &op2->ors_attrs[i].an_name );
2062         }
2063
2064         op2->o_authz = op->o_authz;
2065         op2->o_ndn.bv_val = ptr;
2066         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
2067         op2->o_dn = op2->o_ndn;
2068         op2->o_req_dn.bv_len = op->o_req_dn.bv_len;
2069         op2->o_req_dn.bv_val = ptr;
2070         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
2071         op2->o_req_ndn.bv_len = op->o_req_ndn.bv_len;
2072         op2->o_req_ndn.bv_val = ptr;
2073         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
2074         op2->ors_filterstr.bv_val = ptr;
2075         strcpy( ptr, so->s_filterstr.bv_val );
2076         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
2077
2078         /* Skip the AND/GE clause that we stuck on in front */
2079         if ( so->s_flags & PS_FIX_FILTER ) {
2080                 op2->ors_filter = op->ors_filter->f_and->f_next;
2081                 so->s_flags ^= PS_FIX_FILTER;
2082         } else {
2083                 op2->ors_filter = op->ors_filter;
2084         }
2085         op2->ors_filter = filter_dup( op2->ors_filter, NULL );
2086         so->s_op = op2;
2087
2088         /* Copy any cached group ACLs individually */
2089         op2->o_groups = NULL;
2090         for ( g1=op->o_groups; g1; g1=g1->ga_next ) {
2091                 g2 = ch_malloc( sizeof(GroupAssertion) + g1->ga_len );
2092                 *g2 = *g1;
2093                 strcpy( g2->ga_ndn, g1->ga_ndn );
2094                 g2->ga_next = op2->o_groups;
2095                 op2->o_groups = g2;
2096         }
2097         /* Don't allow any further group caching */
2098         op2->o_do_not_cache = 1;
2099
2100         /* Add op2 to conn so abandon will find us */
2101         op->o_conn->c_n_ops_executing++;
2102         op->o_conn->c_n_ops_completed--;
2103         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op2, o_next );
2104         so->s_flags |= PS_IS_DETACHED;
2105
2106         /* Prevent anyone else from trying to send a result for this op */
2107         op->o_abandon = 1;
2108 }
2109
2110 static int
2111 syncprov_search_response( Operation *op, SlapReply *rs )
2112 {
2113         searchstate *ss = op->o_callback->sc_private;
2114         slap_overinst *on = ss->ss_on;
2115         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2116         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
2117
2118         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
2119                 Attribute *a;
2120                 /* If we got a referral without a referral object, there's
2121                  * something missing that we cannot replicate. Just ignore it.
2122                  * The consumer will abort because we didn't send the expected
2123                  * control.
2124                  */
2125                 if ( !rs->sr_entry ) {
2126                         assert( rs->sr_entry != NULL );
2127                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
2128                         return SLAP_CB_CONTINUE;
2129                 }
2130                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryCSN );
2131                 if ( a == NULL && rs->sr_operational_attrs != NULL ) {
2132                         a = attr_find( rs->sr_operational_attrs, slap_schema.si_ad_entryCSN );
2133                 }
2134                 if ( a ) {
2135                         int i, sid;
2136                         sid = slap_parse_csn_sid( &a->a_nvals[0] );
2137
2138                         /* Don't send changed entries back to the originator */
2139                         if ( sid == srs->sr_state.sid && srs->sr_state.numcsns ) {
2140                                 Debug( LDAP_DEBUG_SYNC,
2141                                         "Entry %s changed by peer, ignored\n",
2142                                         rs->sr_entry->e_name.bv_val, 0, 0 );
2143                                 return LDAP_SUCCESS;
2144                         }
2145
2146                         /* If not a persistent search */
2147                         if ( !ss->ss_so ) {
2148                                 /* Make sure entry is less than the snapshot'd contextCSN */
2149                                 for ( i=0; i<ss->ss_numcsns; i++ ) {
2150                                         if ( sid == ss->ss_sids[i] && ber_bvcmp( &a->a_nvals[0],
2151                                                 &ss->ss_ctxcsn[i] ) > 0 ) {
2152                                                 Debug( LDAP_DEBUG_SYNC,
2153                                                         "Entry %s CSN %s greater than snapshot %s\n",
2154                                                         rs->sr_entry->e_name.bv_val,
2155                                                         a->a_nvals[0].bv_val,
2156                                                         ss->ss_ctxcsn[i].bv_val );
2157                                                 return LDAP_SUCCESS;
2158                                         }
2159                                 }
2160                         }
2161
2162                         /* Don't send old entries twice */
2163                         if ( srs->sr_state.ctxcsn ) {
2164                                 for ( i=0; i<srs->sr_state.numcsns; i++ ) {
2165                                         if ( sid == srs->sr_state.sids[i] &&
2166                                                 ber_bvcmp( &a->a_nvals[0],
2167                                                         &srs->sr_state.ctxcsn[i] )<= 0 ) {
2168                                                 Debug( LDAP_DEBUG_SYNC,
2169                                                         "Entry %s CSN %s older or equal to ctx %s\n",
2170                                                         rs->sr_entry->e_name.bv_val,
2171                                                         a->a_nvals[0].bv_val,
2172                                                         srs->sr_state.ctxcsn[i].bv_val );
2173                                                 return LDAP_SUCCESS;
2174                                         }
2175                                 }
2176                         }
2177                 }
2178                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
2179                         op->o_tmpmemctx );
2180                 rs->sr_ctrls[1] = NULL;
2181                 /* If we're in delta-sync mode, always send a cookie */
2182                 if ( si->si_nopres && si->si_usehint && a ) {
2183                         struct berval cookie;
2184                         slap_compose_sync_cookie( op, &cookie, a->a_nvals, srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
2185                         rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
2186                                 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 1, &cookie );
2187                 } else {
2188                         rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
2189                                 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
2190                 }
2191         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
2192                 struct berval cookie;
2193
2194                 if ( ss->ss_flags & SS_CHANGED ) {
2195                         slap_compose_sync_cookie( op, &cookie, ss->ss_ctxcsn,
2196                                 srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
2197
2198                         Debug( LDAP_DEBUG_SYNC, "syncprov_search_response: cookie=%s\n", cookie.bv_val, 0, 0 );
2199                 }
2200
2201                 /* Is this a regular refresh?
2202                  * Note: refresh never gets here if there were no changes
2203                  */
2204                 if ( !ss->ss_so ) {
2205                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
2206                                 op->o_tmpmemctx );
2207                         rs->sr_ctrls[1] = NULL;
2208                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
2209                                 0, 1, &cookie, ( ss->ss_flags & SS_PRESENT ) ?  LDAP_SYNC_REFRESH_PRESENTS :
2210                                         LDAP_SYNC_REFRESH_DELETES );
2211                         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
2212                 } else {
2213                 /* It's RefreshAndPersist, transition to Persist phase */
2214                         syncprov_sendinfo( op, rs, ( ss->ss_flags & SS_PRESENT ) ?
2215                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
2216                                 ( ss->ss_flags & SS_CHANGED ) ? &cookie : NULL,
2217                                 1, NULL, 0 );
2218                         if ( ss->ss_flags & SS_CHANGED )
2219                                 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
2220
2221                         /* Detach this Op from frontend control */
2222                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
2223
2224                         /* But not if this connection was closed along the way */
2225                         if ( op->o_abandon ) {
2226                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
2227                                 /* syncprov_ab_cleanup will free this syncop */
2228                                 return SLAPD_ABANDON;
2229
2230                         } else {
2231                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
2232                                 /* Turn off the refreshing flag */
2233                                 ss->ss_so->s_flags ^= PS_IS_REFRESHING;
2234
2235                                 syncprov_detach_op( op, ss->ss_so, on );
2236
2237                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
2238
2239                                 /* If there are queued responses, fire them off */
2240                                 if ( ss->ss_so->s_res )
2241                                         syncprov_qstart( ss->ss_so );
2242                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
2243                         }
2244
2245                         return LDAP_SUCCESS;
2246                 }
2247         }
2248
2249         return SLAP_CB_CONTINUE;
2250 }
2251
2252 static int
2253 syncprov_op_search( Operation *op, SlapReply *rs )
2254 {
2255         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
2256         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2257         slap_callback   *cb;
2258         int gotstate = 0, changed = 0, do_present = 0;
2259         syncops *sop = NULL;
2260         searchstate *ss;
2261         sync_control *srs;
2262         BerVarray ctxcsn;
2263         int i, *sids, numcsns;
2264         struct berval mincsn;
2265
2266         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
2267
2268         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
2269                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
2270                 return rs->sr_err;
2271         }
2272
2273         srs = op->o_controls[slap_cids.sc_LDAPsync];
2274
2275         /* If this is a persistent search, set it up right away */
2276         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
2277                 syncops so = {0};
2278                 fbase_cookie fc;
2279                 opcookie opc;
2280                 slap_callback sc;
2281
2282                 fc.fss = &so;
2283                 fc.fbase = 0;
2284                 so.s_eid = NOID;
2285                 so.s_op = op;
2286                 so.s_flags = PS_IS_REFRESHING | PS_FIND_BASE;
2287                 /* syncprov_findbase expects to be called as a callback... */
2288                 sc.sc_private = &opc;
2289                 opc.son = on;
2290                 ldap_pvt_thread_mutex_init( &so.s_mutex );
2291                 cb = op->o_callback;
2292                 op->o_callback = &sc;
2293                 rs->sr_err = syncprov_findbase( op, &fc );
2294                 op->o_callback = cb;
2295                 ldap_pvt_thread_mutex_destroy( &so.s_mutex );
2296
2297                 if ( rs->sr_err != LDAP_SUCCESS ) {
2298                         send_ldap_result( op, rs );
2299                         return rs->sr_err;
2300                 }
2301                 sop = ch_malloc( sizeof( syncops ));
2302                 *sop = so;
2303                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
2304                 sop->s_rid = srs->sr_state.rid;
2305                 sop->s_sid = srs->sr_state.sid;
2306                 sop->s_inuse = 1;
2307
2308                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
2309                 sop->s_next = si->si_ops;
2310                 si->si_ops = sop;
2311                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
2312         }
2313
2314         /* snapshot the ctxcsn */
2315         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2316         numcsns = si->si_numcsns;
2317         if ( numcsns ) {
2318                 ber_bvarray_dup_x( &ctxcsn, si->si_ctxcsn, op->o_tmpmemctx );
2319                 sids = op->o_tmpalloc( numcsns * sizeof(int), op->o_tmpmemctx );
2320                 for ( i=0; i<numcsns; i++ )
2321                         sids[i] = si->si_sids[i];
2322         } else {
2323                 ctxcsn = NULL;
2324                 sids = NULL;
2325         }
2326         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2327         
2328         /* If we have a cookie, handle the PRESENT lookups */
2329         if ( srs->sr_state.ctxcsn ) {
2330                 sessionlog *sl;
2331                 int i, j;
2332
2333                 /* If we don't have any CSN of our own yet, pretend nothing
2334                  * has changed.
2335                  */
2336                 if ( !numcsns )
2337                         goto no_change;
2338
2339                 if ( !si->si_nopres )
2340                         do_present = SS_PRESENT;
2341
2342                 /* If there are SIDs we don't recognize in the cookie, drop them */
2343                 for (i=0; i<srs->sr_state.numcsns; ) {
2344                         for (j=0; j<numcsns; j++) {
2345                                 if ( srs->sr_state.sids[i] == sids[j] ) {
2346                                         break;
2347                                 }
2348                         }
2349                         /* not found */
2350                         if ( j == numcsns ) {
2351                                 struct berval tmp = srs->sr_state.ctxcsn[i];
2352                                 j = srs->sr_state.numcsns - 1;
2353                                 srs->sr_state.ctxcsn[i] = srs->sr_state.ctxcsn[j];
2354                                 tmp.bv_len = 0;
2355                                 srs->sr_state.ctxcsn[j] = tmp;
2356                                 srs->sr_state.numcsns = j;
2357                                 srs->sr_state.sids[i] = srs->sr_state.sids[j];
2358                                 continue;
2359                         }
2360                         i++;
2361                 }
2362
2363                 /* Find the smallest CSN */
2364                 mincsn = srs->sr_state.ctxcsn[0];
2365                 for ( i=1; i<srs->sr_state.numcsns; i++ ) {
2366                         if ( ber_bvcmp( &mincsn, &srs->sr_state.ctxcsn[i] ) > 0 )
2367                                 mincsn = srs->sr_state.ctxcsn[i];
2368                 }
2369
2370                 /* If nothing has changed, shortcut it */
2371                 if ( srs->sr_state.numcsns == numcsns ) {
2372                         int i, j;
2373                         for ( i=0; i<srs->sr_state.numcsns; i++ ) {
2374                                 for ( j=0; j<numcsns; j++ ) {
2375                                         if ( srs->sr_state.sids[i] != sids[j] )
2376                                                 continue;
2377                                         if ( !bvmatch( &srs->sr_state.ctxcsn[i], &ctxcsn[j] ))
2378                                                 changed = SS_CHANGED;
2379                                         break;
2380                                 }
2381                                 if ( changed )
2382                                         break;
2383                         }
2384                         if ( !changed ) {
2385                                 do_present = 0;
2386 no_change:              if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
2387                                         LDAPControl     *ctrls[2];
2388
2389                                         ctrls[0] = NULL;
2390                                         ctrls[1] = NULL;
2391                                         syncprov_done_ctrl( op, rs, ctrls, 0, 0,
2392                                                 NULL, LDAP_SYNC_REFRESH_DELETES );
2393                                         rs->sr_ctrls = ctrls;
2394                                         rs->sr_err = LDAP_SUCCESS;
2395                                         send_ldap_result( op, rs );
2396                                         rs->sr_ctrls = NULL;
2397                                         return rs->sr_err;
2398                                 }
2399                                 goto shortcut;
2400                         }
2401                 } else {
2402                         /* consumer doesn't have the right number of CSNs */
2403                         changed = SS_CHANGED;
2404                 }
2405                 /* Do we have a sessionlog for this search? */
2406                 sl=si->si_logs;
2407                 if ( sl ) {
2408                         ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
2409                         /* Are there any log entries, and is the consumer state
2410                          * present in the session log?
2411                          */
2412                         if ( sl->sl_num > 0 && ber_bvcmp( &mincsn, &sl->sl_mincsn ) >= 0 ) {
2413                                 do_present = 0;
2414                                 /* mutex is unlocked in playlog */
2415                                 syncprov_playlog( op, rs, sl, srs, ctxcsn, numcsns, sids );
2416                         } else {
2417                                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
2418                         }
2419                 }
2420                 /* Is the CSN still present in the database? */
2421                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
2422                         /* No, so a reload is required */
2423                         /* the 2.2 consumer doesn't send this hint */
2424                         if ( si->si_usehint && srs->sr_rhint == 0 ) {
2425                                 if ( ctxcsn )
2426                                         ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
2427                                 if ( sids )
2428                                         op->o_tmpfree( sids, op->o_tmpmemctx );
2429                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
2430                                 return rs->sr_err;
2431                         }
2432                         if ( srs->sr_state.ctxcsn ) {
2433                                 ber_bvarray_free_x( srs->sr_state.ctxcsn, op->o_tmpmemctx );
2434                                 srs->sr_state.ctxcsn = NULL;
2435                         }
2436                         if ( srs->sr_state.sids ) {
2437                                 slap_sl_free( srs->sr_state.sids, op->o_tmpmemctx );
2438                                 srs->sr_state.sids = NULL;
2439                         }
2440                         srs->sr_state.numcsns = 0;
2441                 } else {
2442                         gotstate = 1;
2443                         /* If changed and doing Present lookup, send Present UUIDs */
2444                         if ( do_present && syncprov_findcsn( op, FIND_PRESENT ) !=
2445                                 LDAP_SUCCESS ) {
2446                                 if ( ctxcsn )
2447                                         ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
2448                                 if ( sids )
2449                                         op->o_tmpfree( sids, op->o_tmpmemctx );
2450                                 send_ldap_result( op, rs );
2451                                 return rs->sr_err;
2452                         }
2453                 }
2454         } else {
2455                 /* No consumer state, assume something has changed */
2456                 changed = SS_CHANGED;
2457         }
2458
2459 shortcut:
2460         /* Append CSN range to search filter, save original filter
2461          * for persistent search evaluation
2462          */
2463         if ( sop ) {
2464                 sop->s_filterstr= op->ors_filterstr;
2465         }
2466
2467         /* If something changed, find the changes */
2468         if ( gotstate && changed ) {
2469                 Filter *fand, *fava;
2470
2471                 fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
2472                 fand->f_choice = LDAP_FILTER_AND;
2473                 fand->f_next = NULL;
2474                 fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
2475                 fand->f_and = fava;
2476                 fava->f_choice = LDAP_FILTER_GE;
2477                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
2478                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
2479 #ifdef LDAP_COMP_MATCH
2480                 fava->f_ava->aa_cf = NULL;
2481 #endif
2482                 ber_dupbv_x( &fava->f_ava->aa_value, &mincsn, op->o_tmpmemctx );
2483                 fava->f_next = op->ors_filter;
2484                 op->ors_filter = fand;
2485                 filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2486                 if ( sop )
2487                         sop->s_flags |= PS_FIX_FILTER;
2488         }
2489
2490         /* Let our callback add needed info to returned entries */
2491         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
2492         ss = (searchstate *)(cb+1);
2493         ss->ss_on = on;
2494         ss->ss_so = sop;
2495         ss->ss_flags = do_present | changed;
2496         ss->ss_ctxcsn = ctxcsn;
2497         ss->ss_numcsns = numcsns;
2498         ss->ss_sids = sids;
2499         cb->sc_response = syncprov_search_response;
2500         cb->sc_cleanup = syncprov_search_cleanup;
2501         cb->sc_private = ss;
2502         cb->sc_next = op->o_callback;
2503         op->o_callback = cb;
2504
2505         /* If this is a persistent search and no changes were reported during
2506          * the refresh phase, just invoke the response callback to transition
2507          * us into persist phase
2508          */
2509         if ( !changed ) {
2510                 rs->sr_err = LDAP_SUCCESS;
2511                 rs->sr_nentries = 0;
2512                 send_ldap_result( op, rs );
2513                 return rs->sr_err;
2514         }
2515         return SLAP_CB_CONTINUE;
2516 }
2517
2518 static int
2519 syncprov_operational(
2520         Operation *op,
2521         SlapReply *rs )
2522 {
2523         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
2524         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2525
2526         /* This prevents generating unnecessarily; frontend will strip
2527          * any statically stored copy.
2528          */
2529         if ( op->o_sync != SLAP_CONTROL_NONE )
2530                 return SLAP_CB_CONTINUE;
2531
2532         if ( rs->sr_entry &&
2533                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
2534
2535                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
2536                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
2537                         Attribute *a, **ap = NULL;
2538
2539                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
2540                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
2541                                         break;
2542                         }
2543
2544                         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2545                         if ( si->si_ctxcsn ) {
2546                                 if ( !a ) {
2547                                         for ( ap = &rs->sr_operational_attrs; *ap;
2548                                                 ap=&(*ap)->a_next );
2549
2550                                         a = attr_alloc( slap_schema.si_ad_contextCSN );
2551                                         *ap = a;
2552                                 }
2553
2554                                 if ( !ap ) {
2555                                         if ( !(rs->sr_flags & REP_ENTRY_MODIFIABLE) ) {
2556                                                 Entry *e = entry_dup( rs->sr_entry );
2557                                                 if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
2558                                                         overlay_entry_release_ov( op, rs->sr_entry, 0, on );
2559                                                         rs->sr_flags ^= REP_ENTRY_MUSTRELEASE;
2560                                                 } else if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
2561                                                         entry_free( rs->sr_entry );
2562                                                 }
2563                                                 rs->sr_entry = e;
2564                                                 rs->sr_flags |=
2565                                                         REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED;
2566                                                 a = attr_find( rs->sr_entry->e_attrs,
2567                                                         slap_schema.si_ad_contextCSN );
2568                                         }
2569                                         if ( a->a_nvals != a->a_vals ) {
2570                                                 ber_bvarray_free( a->a_nvals );
2571                                         }
2572                                         a->a_nvals = NULL;
2573                                         ber_bvarray_free( a->a_vals );
2574                                         a->a_vals = NULL;
2575                                         a->a_numvals = 0;
2576                                 }
2577                                 attr_valadd( a, si->si_ctxcsn, si->si_ctxcsn, si->si_numcsns );
2578                         }
2579                         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2580                 }
2581         }
2582         return SLAP_CB_CONTINUE;
2583 }
2584
2585 enum {
2586         SP_CHKPT = 1,
2587         SP_SESSL,
2588         SP_NOPRES,
2589         SP_USEHINT
2590 };
2591
2592 static ConfigDriver sp_cf_gen;
2593
2594 static ConfigTable spcfg[] = {
2595         { "syncprov-checkpoint", "ops> <minutes", 3, 3, 0, ARG_MAGIC|SP_CHKPT,
2596                 sp_cf_gen, "( OLcfgOvAt:1.1 NAME 'olcSpCheckpoint' "
2597                         "DESC 'ContextCSN checkpoint interval in ops and minutes' "
2598                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2599         { "syncprov-sessionlog", "ops", 2, 2, 0, ARG_INT|ARG_MAGIC|SP_SESSL,
2600                 sp_cf_gen, "( OLcfgOvAt:1.2 NAME 'olcSpSessionlog' "
2601                         "DESC 'Session log size in ops' "
2602                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
2603         { "syncprov-nopresent", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_NOPRES,
2604                 sp_cf_gen, "( OLcfgOvAt:1.3 NAME 'olcSpNoPresent' "
2605                         "DESC 'Omit Present phase processing' "
2606                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
2607         { "syncprov-reloadhint", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_USEHINT,
2608                 sp_cf_gen, "( OLcfgOvAt:1.4 NAME 'olcSpReloadHint' "
2609                         "DESC 'Observe Reload Hint in Request control' "
2610                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
2611         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2612 };
2613
2614 static ConfigOCs spocs[] = {
2615         { "( OLcfgOvOc:1.1 "
2616                 "NAME 'olcSyncProvConfig' "
2617                 "DESC 'SyncRepl Provider configuration' "
2618                 "SUP olcOverlayConfig "
2619                 "MAY ( olcSpCheckpoint "
2620                         "$ olcSpSessionlog "
2621                         "$ olcSpNoPresent "
2622                         "$ olcSpReloadHint "
2623                 ") )",
2624                         Cft_Overlay, spcfg },
2625         { NULL, 0, NULL }
2626 };
2627
2628 static int
2629 sp_cf_gen(ConfigArgs *c)
2630 {
2631         slap_overinst           *on = (slap_overinst *)c->bi;
2632         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2633         int rc = 0;
2634
2635         if ( c->op == SLAP_CONFIG_EMIT ) {
2636                 switch ( c->type ) {
2637                 case SP_CHKPT:
2638                         if ( si->si_chkops || si->si_chktime ) {
2639                                 struct berval bv;
2640                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2641                                         "%d %d", si->si_chkops, si->si_chktime );
2642                                 if ( bv.bv_len >= sizeof( c->cr_msg ) ) {
2643                                         rc = 1;
2644                                 } else {
2645                                         bv.bv_val = c->cr_msg;
2646                                         value_add_one( &c->rvalue_vals, &bv );
2647                                 }
2648                         } else {
2649                                 rc = 1;
2650                         }
2651                         break;
2652                 case SP_SESSL:
2653                         if ( si->si_logs ) {
2654                                 c->value_int = si->si_logs->sl_size;
2655                         } else {
2656                                 rc = 1;
2657                         }
2658                         break;
2659                 case SP_NOPRES:
2660                         if ( si->si_nopres ) {
2661                                 c->value_int = 1;
2662                         } else {
2663                                 rc = 1;
2664                         }
2665                         break;
2666                 case SP_USEHINT:
2667                         if ( si->si_usehint ) {
2668                                 c->value_int = 1;
2669                         } else {
2670                                 rc = 1;
2671                         }
2672                         break;
2673                 }
2674                 return rc;
2675         } else if ( c->op == LDAP_MOD_DELETE ) {
2676                 switch ( c->type ) {
2677                 case SP_CHKPT:
2678                         si->si_chkops = 0;
2679                         si->si_chktime = 0;
2680                         break;
2681                 case SP_SESSL:
2682                         if ( si->si_logs )
2683                                 si->si_logs->sl_size = 0;
2684                         else
2685                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2686                         break;
2687                 case SP_NOPRES:
2688                         if ( si->si_nopres )
2689                                 si->si_nopres = 0;
2690                         else
2691                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2692                         break;
2693                 case SP_USEHINT:
2694                         if ( si->si_usehint )
2695                                 si->si_usehint = 0;
2696                         else
2697                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2698                         break;
2699                 }
2700                 return rc;
2701         }
2702         switch ( c->type ) {
2703         case SP_CHKPT:
2704                 if ( lutil_atoi( &si->si_chkops, c->argv[1] ) != 0 ) {
2705                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint ops # \"%s\"",
2706                                 c->argv[0], c->argv[1] );
2707                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2708                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2709                         return ARG_BAD_CONF;
2710                 }
2711                 if ( si->si_chkops <= 0 ) {
2712                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint ops # \"%d\"",
2713                                 c->argv[0], si->si_chkops );
2714                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2715                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2716                         return ARG_BAD_CONF;
2717                 }
2718                 if ( lutil_atoi( &si->si_chktime, c->argv[2] ) != 0 ) {
2719                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint time \"%s\"",
2720                                 c->argv[0], c->argv[1] );
2721                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2722                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2723                         return ARG_BAD_CONF;
2724                 }
2725                 if ( si->si_chktime <= 0 ) {
2726                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint time \"%d\"",
2727                                 c->argv[0], si->si_chkops );
2728                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2729                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2730                         return ARG_BAD_CONF;
2731                 }
2732                 si->si_chktime *= 60;
2733                 break;
2734         case SP_SESSL: {
2735                 sessionlog *sl;
2736                 int size = c->value_int;
2737
2738                 if ( size < 0 ) {
2739                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s size %d is negative",
2740                                 c->argv[0], size );
2741                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2742                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2743                         return ARG_BAD_CONF;
2744                 }
2745                 sl = si->si_logs;
2746                 if ( !sl ) {
2747                         sl = ch_malloc( sizeof( sessionlog ) + LDAP_LUTIL_CSNSTR_BUFSIZE );
2748                         sl->sl_mincsn.bv_val = (char *)(sl+1);
2749                         sl->sl_mincsn.bv_len = 0;
2750                         sl->sl_num = 0;
2751                         sl->sl_head = sl->sl_tail = NULL;
2752                         ldap_pvt_thread_mutex_init( &sl->sl_mutex );
2753                         si->si_logs = sl;
2754                 }
2755                 sl->sl_size = size;
2756                 }
2757                 break;
2758         case SP_NOPRES:
2759                 si->si_nopres = c->value_int;
2760                 break;
2761         case SP_USEHINT:
2762                 si->si_usehint = c->value_int;
2763                 break;
2764         }
2765         return rc;
2766 }
2767
2768 /* ITS#3456 we cannot run this search on the main thread, must use a
2769  * child thread in order to insure we have a big enough stack.
2770  */
2771 static void *
2772 syncprov_db_otask(
2773         void *ptr
2774 )
2775 {
2776         syncprov_findcsn( ptr, FIND_MAXCSN );
2777         return NULL;
2778 }
2779
2780 /* Read any existing contextCSN from the underlying db.
2781  * Then search for any entries newer than that. If no value exists,
2782  * just generate it. Cache whatever result.
2783  */
2784 static int
2785 syncprov_db_open(
2786         BackendDB *be,
2787         ConfigReply *cr
2788 )
2789 {
2790         slap_overinst   *on = (slap_overinst *) be->bd_info;
2791         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2792
2793         Connection conn = { 0 };
2794         OperationBuffer opbuf;
2795         Operation *op;
2796         Entry *e = NULL;
2797         Attribute *a;
2798         int rc;
2799         void *thrctx = NULL;
2800
2801         if ( !SLAP_LASTMOD( be )) {
2802                 Debug( LDAP_DEBUG_ANY,
2803                         "syncprov_db_open: invalid config, lastmod must be enabled\n", 0, 0, 0 );
2804                 return -1;
2805         }
2806
2807         if ( slapMode & SLAP_TOOL_MODE ) {
2808                 return 0;
2809         }
2810
2811         rc = overlay_register_control( be, LDAP_CONTROL_SYNC );
2812         if ( rc ) {
2813                 return rc;
2814         }
2815
2816         thrctx = ldap_pvt_thread_pool_context();
2817         connection_fake_init( &conn, &opbuf, thrctx );
2818         op = &opbuf.ob_op;
2819         op->o_bd = be;
2820         op->o_dn = be->be_rootdn;
2821         op->o_ndn = be->be_rootndn;
2822
2823         rc = overlay_entry_get_ov( op, be->be_nsuffix, NULL,
2824                 slap_schema.si_ad_contextCSN, 0, &e, on );
2825
2826         if ( e ) {
2827                 ldap_pvt_thread_t tid;
2828
2829                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
2830                 if ( a ) {
2831                         ber_bvarray_dup_x( &si->si_ctxcsn, a->a_vals, NULL );
2832                         si->si_numcsns = a->a_numvals;
2833                         si->si_sids = slap_parse_csn_sids( si->si_ctxcsn, a->a_numvals, NULL );
2834                 }
2835                 overlay_entry_release_ov( op, e, 0, on );
2836                 if ( si->si_ctxcsn && !SLAP_DBCLEAN( be )) {
2837                         op->o_req_dn = be->be_suffix[0];
2838                         op->o_req_ndn = be->be_nsuffix[0];
2839                         op->ors_scope = LDAP_SCOPE_SUBTREE;
2840                         ldap_pvt_thread_create( &tid, 0, syncprov_db_otask, op );
2841                         ldap_pvt_thread_join( tid, NULL );
2842                 }
2843         }
2844
2845         /* Didn't find a contextCSN, should we generate one? */
2846         if ( !si->si_ctxcsn ) {
2847                 char csnbuf[ LDAP_LUTIL_CSNSTR_BUFSIZE ];
2848                 struct berval csn;
2849
2850                 if ( SLAP_SYNC_SHADOW( op->o_bd )) {
2851                 /* If we're also a consumer, then don't generate anything.
2852                  * Wait for our provider to send it to us, or for a local
2853                  * modify if we have multimaster.
2854                  */
2855                         goto out;
2856                 }
2857                 csn.bv_val = csnbuf;
2858                 csn.bv_len = sizeof( csnbuf );
2859                 slap_get_csn( op, &csn, 0 );
2860                 value_add_one( &si->si_ctxcsn, &csn );
2861                 si->si_numcsns = 1;
2862                 si->si_sids = ch_malloc( sizeof(int) );
2863                 si->si_sids[0] = slap_serverID;
2864
2865                 /* make sure we do a checkpoint on close */
2866                 si->si_numops++;
2867         }
2868
2869 out:
2870         op->o_bd->bd_info = (BackendInfo *)on;
2871         return 0;
2872 }
2873
2874 /* Write the current contextCSN into the underlying db.
2875  */
2876 static int
2877 syncprov_db_close(
2878         BackendDB *be,
2879         ConfigReply *cr
2880 )
2881 {
2882     slap_overinst   *on = (slap_overinst *) be->bd_info;
2883     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2884
2885         if ( slapMode & SLAP_TOOL_MODE ) {
2886                 return 0;
2887         }
2888         if ( si->si_numops ) {
2889                 Connection conn = {0};
2890                 OperationBuffer opbuf;
2891                 Operation *op;
2892                 SlapReply rs = {REP_RESULT};
2893                 void *thrctx;
2894
2895                 thrctx = ldap_pvt_thread_pool_context();
2896                 connection_fake_init( &conn, &opbuf, thrctx );
2897                 op = &opbuf.ob_op;
2898                 op->o_bd = be;
2899                 op->o_dn = be->be_rootdn;
2900                 op->o_ndn = be->be_rootndn;
2901                 syncprov_checkpoint( op, &rs, on );
2902         }
2903
2904     return 0;
2905 }
2906
2907 static int
2908 syncprov_db_init(
2909         BackendDB *be,
2910         ConfigReply *cr
2911 )
2912 {
2913         slap_overinst   *on = (slap_overinst *)be->bd_info;
2914         syncprov_info_t *si;
2915
2916         if ( SLAP_ISGLOBALOVERLAY( be ) ) {
2917                 Debug( LDAP_DEBUG_ANY,
2918                         "syncprov must be instantiated within a database.\n",
2919                         0, 0, 0 );
2920                 return 1;
2921         }
2922
2923         si = ch_calloc(1, sizeof(syncprov_info_t));
2924         on->on_bi.bi_private = si;
2925         ldap_pvt_thread_rdwr_init( &si->si_csn_rwlock );
2926         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
2927         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
2928
2929         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
2930         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
2931         csn_anlist[1].an_desc = slap_schema.si_ad_entryUUID;
2932         csn_anlist[1].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2933
2934         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
2935         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2936
2937         return 0;
2938 }
2939
2940 static int
2941 syncprov_db_destroy(
2942         BackendDB *be,
2943         ConfigReply *cr
2944 )
2945 {
2946         slap_overinst   *on = (slap_overinst *)be->bd_info;
2947         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2948
2949         if ( si ) {
2950                 if ( si->si_logs ) {
2951                         slog_entry *se = si->si_logs->sl_head;
2952
2953                         while ( se ) {
2954                                 slog_entry *se_next = se->se_next;
2955                                 ch_free( se );
2956                                 se = se_next;
2957                         }
2958                                 
2959                         ch_free( si->si_logs );
2960                 }
2961                 if ( si->si_ctxcsn )
2962                         ber_bvarray_free( si->si_ctxcsn );
2963                 if ( si->si_sids )
2964                         ch_free( si->si_sids );
2965                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
2966                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
2967                 ldap_pvt_thread_rdwr_destroy( &si->si_csn_rwlock );
2968                 ch_free( si );
2969         }
2970
2971         return 0;
2972 }
2973
2974 static int syncprov_parseCtrl (
2975         Operation *op,
2976         SlapReply *rs,
2977         LDAPControl *ctrl )
2978 {
2979         ber_tag_t tag;
2980         BerElementBuffer berbuf;
2981         BerElement *ber = (BerElement *)&berbuf;
2982         ber_int_t mode;
2983         ber_len_t len;
2984         struct berval cookie = BER_BVNULL;
2985         sync_control *sr;
2986         int rhint = 0;
2987
2988         if ( op->o_sync != SLAP_CONTROL_NONE ) {
2989                 rs->sr_text = "Sync control specified multiple times";
2990                 return LDAP_PROTOCOL_ERROR;
2991         }
2992
2993         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
2994                 rs->sr_text = "Sync control specified with pagedResults control";
2995                 return LDAP_PROTOCOL_ERROR;
2996         }
2997
2998         if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
2999                 rs->sr_text = "Sync control value is absent";
3000                 return LDAP_PROTOCOL_ERROR;
3001         }
3002
3003         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
3004                 rs->sr_text = "Sync control value is empty";
3005                 return LDAP_PROTOCOL_ERROR;
3006         }
3007
3008         /* Parse the control value
3009          *      syncRequestValue ::= SEQUENCE {
3010          *              mode   ENUMERATED {
3011          *                      -- 0 unused
3012          *                      refreshOnly             (1),
3013          *                      -- 2 reserved
3014          *                      refreshAndPersist       (3)
3015          *              },
3016          *              cookie  syncCookie OPTIONAL
3017          *      }
3018          */
3019
3020         ber_init2( ber, &ctrl->ldctl_value, 0 );
3021
3022         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
3023                 rs->sr_text = "Sync control : mode decoding error";
3024                 return LDAP_PROTOCOL_ERROR;
3025         }
3026
3027         switch( mode ) {
3028         case LDAP_SYNC_REFRESH_ONLY:
3029                 mode = SLAP_SYNC_REFRESH;
3030                 break;
3031         case LDAP_SYNC_REFRESH_AND_PERSIST:
3032                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
3033                 break;
3034         default:
3035                 rs->sr_text = "Sync control : unknown update mode";
3036                 return LDAP_PROTOCOL_ERROR;
3037         }
3038
3039         tag = ber_peek_tag( ber, &len );
3040
3041         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
3042                 if (( ber_scanf( ber, /*{*/ "m", &cookie )) == LBER_ERROR ) {
3043                         rs->sr_text = "Sync control : cookie decoding error";
3044                         return LDAP_PROTOCOL_ERROR;
3045                 }
3046                 tag = ber_peek_tag( ber, &len );
3047         }
3048         if ( tag == LDAP_TAG_RELOAD_HINT ) {
3049                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
3050                         rs->sr_text = "Sync control : rhint decoding error";
3051                         return LDAP_PROTOCOL_ERROR;
3052                 }
3053         }
3054         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
3055                         rs->sr_text = "Sync control : decoding error";
3056                         return LDAP_PROTOCOL_ERROR;
3057         }
3058         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
3059         sr->sr_rhint = rhint;
3060         if (!BER_BVISNULL(&cookie)) {
3061                 ber_dupbv_x( &sr->sr_state.octet_str, &cookie, op->o_tmpmemctx );
3062                 /* If parse fails, pretend no cookie was sent */
3063                 if ( slap_parse_sync_cookie( &sr->sr_state, op->o_tmpmemctx ) ||
3064                         sr->sr_state.rid == -1 ) {
3065                         if ( sr->sr_state.ctxcsn ) {
3066                                 ber_bvarray_free_x( sr->sr_state.ctxcsn, op->o_tmpmemctx );
3067                                 sr->sr_state.ctxcsn = NULL;
3068                         }
3069                         sr->sr_state.numcsns = 0;
3070                 }
3071         }
3072
3073         op->o_controls[slap_cids.sc_LDAPsync] = sr;
3074
3075         op->o_sync = ctrl->ldctl_iscritical
3076                 ? SLAP_CONTROL_CRITICAL
3077                 : SLAP_CONTROL_NONCRITICAL;
3078
3079         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
3080
3081         return LDAP_SUCCESS;
3082 }
3083
3084 /* This overlay is set up for dynamic loading via moduleload. For static
3085  * configuration, you'll need to arrange for the slap_overinst to be
3086  * initialized and registered by some other function inside slapd.
3087  */
3088
3089 static slap_overinst            syncprov;
3090
3091 int
3092 syncprov_initialize()
3093 {
3094         int rc;
3095
3096         rc = register_supported_control( LDAP_CONTROL_SYNC,
3097                 SLAP_CTRL_SEARCH, NULL,
3098                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
3099         if ( rc != LDAP_SUCCESS ) {
3100                 Debug( LDAP_DEBUG_ANY,
3101                         "syncprov_init: Failed to register control %d\n", rc, 0, 0 );
3102                 return rc;
3103         }
3104
3105         syncprov.on_bi.bi_type = "syncprov";
3106         syncprov.on_bi.bi_db_init = syncprov_db_init;
3107         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
3108         syncprov.on_bi.bi_db_open = syncprov_db_open;
3109         syncprov.on_bi.bi_db_close = syncprov_db_close;
3110
3111         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
3112         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
3113
3114         syncprov.on_bi.bi_op_add = syncprov_op_mod;
3115         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
3116         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
3117         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
3118         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
3119         syncprov.on_bi.bi_op_search = syncprov_op_search;
3120         syncprov.on_bi.bi_extended = syncprov_op_extended;
3121         syncprov.on_bi.bi_operational = syncprov_operational;
3122
3123         syncprov.on_bi.bi_cf_ocs = spocs;
3124
3125         generic_filter.f_desc = slap_schema.si_ad_objectClass;
3126
3127         rc = config_register_schema( spcfg, spocs );
3128         if ( rc ) return rc;
3129
3130         return overlay_register( &syncprov );
3131 }
3132
3133 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
3134 int
3135 init_module( int argc, char *argv[] )
3136 {
3137         return syncprov_initialize();
3138 }
3139 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
3140
3141 #endif /* defined(SLAPD_OVER_SYNCPROV) */