]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
31da3e1a0d429f9d46223849a42ef5847bccf576
[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         Debug( LDAP_DEBUG_SYNC, "syncprov_sendresp: cookie=%s\n", cookie.bv_val, 0, 0 );
789
790         e_uuid.e_attrs = &a_uuid;
791         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
792         a_uuid.a_nvals = &opc->suuid;
793         rs.sr_err = syncprov_state_ctrl( op, &rs, &e_uuid,
794                 mode, ctrls, 0, 1, &cookie );
795         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
796
797         rs.sr_ctrls = ctrls;
798         op->o_bd->bd_info = (BackendInfo *)on->on_info;
799         switch( mode ) {
800         case LDAP_SYNC_ADD:
801                 rs.sr_entry = *e;
802                 if ( rs.sr_entry->e_private )
803                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
804                 if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
805                         rs.sr_ref = get_entry_referrals( op, rs.sr_entry );
806                         rs.sr_err = send_search_reference( op, &rs );
807                         ber_bvarray_free( rs.sr_ref );
808                         if ( !rs.sr_entry )
809                                 *e = NULL;
810                         break;
811                 }
812                 /* fallthru */
813         case LDAP_SYNC_MODIFY:
814                 rs.sr_entry = *e;
815                 if ( rs.sr_entry->e_private )
816                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
817                 rs.sr_attrs = op->ors_attrs;
818                 rs.sr_err = send_search_entry( op, &rs );
819                 if ( !rs.sr_entry )
820                         *e = NULL;
821                 break;
822         case LDAP_SYNC_DELETE:
823                 e_uuid.e_attrs = NULL;
824                 e_uuid.e_name = opc->sdn;
825                 e_uuid.e_nname = opc->sndn;
826                 rs.sr_entry = &e_uuid;
827                 if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
828                         struct berval bv = BER_BVNULL;
829                         rs.sr_ref = &bv;
830                         rs.sr_err = send_search_reference( op, &rs );
831                 } else {
832                         rs.sr_err = send_search_entry( op, &rs );
833                 }
834                 break;
835         default:
836                 assert(0);
837         }
838         /* In case someone else freed it already? */
839         if ( rs.sr_ctrls ) {
840                 op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
841                 rs.sr_ctrls = NULL;
842         }
843
844         return rs.sr_err;
845 }
846
847 static void
848 syncprov_qstart( syncops *so );
849
850 /* Play back queued responses */
851 static int
852 syncprov_qplay( Operation *op, syncops *so )
853 {
854         slap_overinst *on = LDAP_SLIST_FIRST(&so->s_op->o_extra)->oe_key;
855         syncres *sr;
856         Entry *e;
857         opcookie opc;
858         int rc = 0;
859
860         opc.son = on;
861
862         do {
863                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
864                 sr = so->s_res;
865                 if ( sr )
866                         so->s_res = sr->s_next;
867                 if ( !so->s_res )
868                         so->s_restail = NULL;
869                 /* Exit loop with mutex held */
870                 if ( !sr || so->s_op->o_abandon )
871                         break;
872                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
873
874                 if ( sr->s_mode == LDAP_SYNC_NEW_COOKIE ) {
875                     SlapReply rs = { REP_INTERMEDIATE };
876
877                     rc = syncprov_sendinfo( op, &rs, LDAP_TAG_SYNC_NEW_COOKIE,
878                                 &sr->s_csn, 0, NULL, 0 );
879                 } else {
880                         opc.sdn = sr->s_dn;
881                         opc.sndn = sr->s_ndn;
882                         opc.suuid = sr->s_uuid;
883                         opc.sctxcsn = sr->s_csn;
884                         opc.sreference = sr->s_isreference;
885                         e = NULL;
886
887                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
888                                 rc = overlay_entry_get_ov( op, &opc.sndn, NULL, NULL, 0, &e, on );
889                                 if ( rc ) {
890                                         Debug( LDAP_DEBUG_SYNC, "syncprov_qplay: failed to get %s, "
891                                                 "error (%d), ignoring...\n", opc.sndn.bv_val, rc, 0 );
892                                         ch_free( sr );
893                                         rc = 0;
894                                         continue;
895                                 }
896                         }
897                         rc = syncprov_sendresp( op, &opc, so, &e, sr->s_mode );
898
899                         if ( e ) {
900                                 overlay_entry_release_ov( op, e, 0, on );
901                         }
902                 }
903
904                 ch_free( sr );
905
906                 /* Exit loop with mutex held */
907                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
908
909         } while (0);
910
911         /* We now only send one change at a time, to prevent one
912          * psearch from hogging all the CPU. Resubmit this task if
913          * there are more responses queued and no errors occurred.
914          */
915
916         if ( rc == 0 && so->s_res ) {
917                 syncprov_qstart( so );
918         } else {
919                 so->s_flags ^= PS_TASK_QUEUED;
920         }
921
922         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
923         return rc;
924 }
925
926 /* task for playing back queued responses */
927 static void *
928 syncprov_qtask( void *ctx, void *arg )
929 {
930         syncops *so = arg;
931         OperationBuffer opbuf;
932         Operation *op;
933         BackendDB be;
934         int rc;
935
936         op = &opbuf.ob_op;
937         *op = *so->s_op;
938         op->o_hdr = &opbuf.ob_hdr;
939         op->o_controls = opbuf.ob_controls;
940         memset( op->o_controls, 0, sizeof(opbuf.ob_controls) );
941
942         *op->o_hdr = *so->s_op->o_hdr;
943
944         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx, 1);
945         op->o_tmpmfuncs = &slap_sl_mfuncs;
946         op->o_threadctx = ctx;
947
948         /* syncprov_qplay expects a fake db */
949         be = *so->s_op->o_bd;
950         be.be_flags |= SLAP_DBFLAG_OVERLAY;
951         op->o_bd = &be;
952         LDAP_SLIST_FIRST(&op->o_extra) = NULL;
953         op->o_callback = NULL;
954
955         rc = syncprov_qplay( op, so );
956
957         /* decrement use count... */
958         syncprov_free_syncop( so );
959
960         return NULL;
961 }
962
963 /* Start the task to play back queued psearch responses */
964 static void
965 syncprov_qstart( syncops *so )
966 {
967         so->s_flags |= PS_TASK_QUEUED;
968         so->s_inuse++;
969         ldap_pvt_thread_pool_submit( &connection_pool, 
970                 syncprov_qtask, so );
971 }
972
973 /* Queue a persistent search response */
974 static int
975 syncprov_qresp( opcookie *opc, syncops *so, int mode )
976 {
977         syncres *sr;
978         int srsize;
979         struct berval cookie = opc->sctxcsn;
980
981         if ( mode == LDAP_SYNC_NEW_COOKIE ) {
982                 syncprov_info_t *si = opc->son->on_bi.bi_private;
983
984                 slap_compose_sync_cookie( NULL, &cookie, si->si_ctxcsn,
985                         so->s_rid, slap_serverID ? slap_serverID : -1);
986         }
987
988         srsize = sizeof(syncres) + opc->suuid.bv_len + 1 +
989                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1;
990         if ( cookie.bv_len )
991                 srsize += cookie.bv_len + 1;
992         sr = ch_malloc( srsize );
993         sr->s_next = NULL;
994         sr->s_dn.bv_val = (char *)(sr + 1);
995         sr->s_dn.bv_len = opc->sdn.bv_len;
996         sr->s_mode = mode;
997         sr->s_isreference = opc->sreference;
998         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val,
999                  opc->sdn.bv_val ) + 1;
1000         sr->s_ndn.bv_len = opc->sndn.bv_len;
1001         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val,
1002                  opc->sndn.bv_val ) + 1;
1003         sr->s_uuid.bv_len = opc->suuid.bv_len;
1004         AC_MEMCPY( sr->s_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1005         if ( cookie.bv_len ) {
1006                 sr->s_csn.bv_val = sr->s_uuid.bv_val + sr->s_uuid.bv_len + 1;
1007                 strcpy( sr->s_csn.bv_val, cookie.bv_val );
1008         } else {
1009                 sr->s_csn.bv_val = NULL;
1010         }
1011         sr->s_csn.bv_len = cookie.bv_len;
1012
1013         if ( mode == LDAP_SYNC_NEW_COOKIE && cookie.bv_val ) {
1014                 ch_free( cookie.bv_val );
1015         }
1016
1017         ldap_pvt_thread_mutex_lock( &so->s_mutex );
1018         if ( !so->s_res ) {
1019                 so->s_res = sr;
1020         } else {
1021                 so->s_restail->s_next = sr;
1022         }
1023         so->s_restail = sr;
1024
1025         /* If the base of the psearch was modified, check it next time round */
1026         if ( so->s_flags & PS_WROTE_BASE ) {
1027                 so->s_flags ^= PS_WROTE_BASE;
1028                 so->s_flags |= PS_FIND_BASE;
1029         }
1030         if (( so->s_flags & (PS_IS_DETACHED|PS_TASK_QUEUED)) == PS_IS_DETACHED ) {
1031                 syncprov_qstart( so );
1032         }
1033         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
1034         return LDAP_SUCCESS;
1035 }
1036
1037 static int
1038 syncprov_drop_psearch( syncops *so, int lock )
1039 {
1040         if ( so->s_flags & PS_IS_DETACHED ) {
1041                 if ( lock )
1042                         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
1043                 so->s_op->o_conn->c_n_ops_executing--;
1044                 so->s_op->o_conn->c_n_ops_completed++;
1045                 LDAP_STAILQ_REMOVE( &so->s_op->o_conn->c_ops, so->s_op, Operation,
1046                         o_next );
1047                 if ( lock )
1048                         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
1049         }
1050         syncprov_free_syncop( so );
1051
1052         return 0;
1053 }
1054
1055 static int
1056 syncprov_ab_cleanup( Operation *op, SlapReply *rs )
1057 {
1058         slap_callback *sc = op->o_callback;
1059         op->o_callback = sc->sc_next;
1060         syncprov_drop_psearch( op->o_callback->sc_private, 0 );
1061         op->o_tmpfree( sc, op->o_tmpmemctx );
1062         return 0;
1063 }
1064
1065 static int
1066 syncprov_op_abandon( Operation *op, SlapReply *rs )
1067 {
1068         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1069         syncprov_info_t         *si = on->on_bi.bi_private;
1070         syncops *so, *soprev;
1071
1072         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1073         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
1074                 soprev=so, so=so->s_next ) {
1075                 if ( so->s_op->o_connid == op->o_connid &&
1076                         so->s_op->o_msgid == op->orn_msgid ) {
1077                                 so->s_op->o_abandon = 1;
1078                                 soprev->s_next = so->s_next;
1079                                 break;
1080                 }
1081         }
1082         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1083         if ( so ) {
1084                 /* Is this really a Cancel exop? */
1085                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
1086                         so->s_op->o_cancel = SLAP_CANCEL_ACK;
1087                         rs->sr_err = LDAP_CANCELLED;
1088                         send_ldap_result( so->s_op, rs );
1089                         if ( so->s_flags & PS_IS_DETACHED ) {
1090                                 slap_callback *cb;
1091                                 cb = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1092                                 cb->sc_cleanup = syncprov_ab_cleanup;
1093                                 cb->sc_next = op->o_callback;
1094                                 cb->sc_private = so;
1095                                 return SLAP_CB_CONTINUE;
1096                         }
1097                 }
1098                 syncprov_drop_psearch( so, 0 );
1099         }
1100         return SLAP_CB_CONTINUE;
1101 }
1102
1103 /* Find which persistent searches are affected by this operation */
1104 static void
1105 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
1106 {
1107         slap_overinst *on = opc->son;
1108         syncprov_info_t         *si = on->on_bi.bi_private;
1109
1110         fbase_cookie fc;
1111         syncops *ss, *sprev, *snext;
1112         struct sync_cookie *scook;
1113         Entry *e = NULL;
1114         Attribute *a;
1115         int rc;
1116         struct berval newdn;
1117         int freefdn = 0;
1118         BackendDB *b0 = op->o_bd, db;
1119
1120         fc.fdn = &op->o_req_ndn;
1121         /* compute new DN */
1122         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1123                 struct berval pdn;
1124                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
1125                 else dnParent( fc.fdn, &pdn );
1126                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
1127                 fc.fdn = &newdn;
1128                 freefdn = 1;
1129         }
1130         if ( op->o_tag != LDAP_REQ_ADD ) {
1131                 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1132                         db = *op->o_bd;
1133                         op->o_bd = &db;
1134                 }
1135                 rc = overlay_entry_get_ov( op, fc.fdn, NULL, NULL, 0, &e, on );
1136                 /* If we're sending responses now, make a copy and unlock the DB */
1137                 if ( e && !saveit ) {
1138                         Entry *e2 = entry_dup( e );
1139                         overlay_entry_release_ov( op, e, 0, on );
1140                         e = e2;
1141                 }
1142                 if ( rc ) {
1143                         op->o_bd = b0;
1144                         return;
1145                 }
1146         } else {
1147                 e = op->ora_e;
1148         }
1149
1150         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
1151                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1152                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1153                 opc->sreference = is_entry_referral( e );
1154                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
1155                 if ( a )
1156                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
1157         } else if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1158                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1159                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1160                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1161                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1162         }
1163
1164         scook = op->o_controls ? op->o_controls[slap_cids.sc_LDAPsync] : NULL;
1165         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1166         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
1167                 sprev = ss, ss=snext)
1168         {
1169                 Operation op2;
1170                 Opheader oh;
1171                 syncmatches *sm;
1172                 int found = 0;
1173
1174                 snext = ss->s_next;
1175                 if ( ss->s_op->o_abandon )
1176                         continue;
1177
1178                 /* Don't send ops back to the originator */
1179                 if ( opc->ssid > 0 && opc->ssid == ss->s_sid ) {
1180                         Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping original sid %03x\n",
1181                                 opc->ssid, 0, 0 );
1182                         continue;
1183                 }
1184
1185                 /* Don't send ops back to the messenger */
1186                 if ( scook && scook->sid > 0 && scook->sid == ss->s_sid ) {
1187                         Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping relayed sid %03x\n",
1188                                 scook->sid, 0, 0 );
1189                         continue;
1190                 }
1191
1192                 /* validate base */
1193                 fc.fss = ss;
1194                 fc.fbase = 0;
1195                 fc.fscope = 0;
1196
1197                 /* If the base of the search is missing, signal a refresh */
1198                 rc = syncprov_findbase( op, &fc );
1199                 if ( rc != LDAP_SUCCESS ) {
1200                         SlapReply rs = {REP_RESULT};
1201                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
1202                                 "search base has changed" );
1203                         sprev->s_next = snext;
1204                         syncprov_drop_psearch( ss, 1 );
1205                         ss = sprev;
1206                         continue;
1207                 }
1208
1209
1210                 /* If we're sending results now, look for this op in old matches */
1211                 if ( !saveit ) {
1212                         syncmatches *old;
1213
1214                         /* Did we modify the search base? */
1215                         if ( dn_match( &op->o_req_ndn, &ss->s_base )) {
1216                                 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1217                                 ss->s_flags |= PS_WROTE_BASE;
1218                                 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1219                         }
1220
1221                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
1222                                 old=sm, sm=sm->sm_next ) {
1223                                 if ( sm->sm_op == ss ) {
1224                                         found = 1;
1225                                         old->sm_next = sm->sm_next;
1226                                         op->o_tmpfree( sm, op->o_tmpmemctx );
1227                                         break;
1228                                 }
1229                         }
1230                 }
1231
1232                 if ( fc.fscope ) {
1233                         op2 = *ss->s_op;
1234                         oh = *op->o_hdr;
1235                         oh.oh_conn = ss->s_op->o_conn;
1236                         oh.oh_connid = ss->s_op->o_connid;
1237                         op2.o_hdr = &oh;
1238                         op2.o_extra = op->o_extra;
1239                 }
1240
1241                 /* check if current o_req_dn is in scope and matches filter */
1242                 if ( fc.fscope && test_filter( &op2, e, ss->s_op->ors_filter ) ==
1243                         LDAP_COMPARE_TRUE ) {
1244                         if ( saveit ) {
1245                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
1246                                 sm->sm_next = opc->smatches;
1247                                 sm->sm_op = ss;
1248                                 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1249                                 ++ss->s_inuse;
1250                                 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1251                                 opc->smatches = sm;
1252                         } else {
1253                                 /* if found send UPDATE else send ADD */
1254                                 syncprov_qresp( opc, ss,
1255                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD );
1256                         }
1257                 } else if ( !saveit && found ) {
1258                         /* send DELETE */
1259                         syncprov_qresp( opc, ss, LDAP_SYNC_DELETE );
1260                 } else if ( !saveit ) {
1261                         syncprov_qresp( opc, ss, LDAP_SYNC_NEW_COOKIE );
1262                 }
1263                 if ( !saveit && found ) {
1264                         /* Decrement s_inuse, was incremented when called
1265                          * with saveit == TRUE
1266                          */
1267                         syncprov_free_syncop( ss );
1268                 }
1269         }
1270         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1271
1272         if ( op->o_tag != LDAP_REQ_ADD && e ) {
1273                 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1274                         op->o_bd = &db;
1275                 }
1276                 overlay_entry_release_ov( op, e, 0, on );
1277                 op->o_bd = b0;
1278         }
1279         if ( freefdn ) {
1280                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
1281         }
1282         op->o_bd = b0;
1283 }
1284
1285 static int
1286 syncprov_op_cleanup( Operation *op, SlapReply *rs )
1287 {
1288         slap_callback *cb = op->o_callback;
1289         opcookie *opc = cb->sc_private;
1290         slap_overinst *on = opc->son;
1291         syncprov_info_t         *si = on->on_bi.bi_private;
1292         syncmatches *sm, *snext;
1293         modtarget *mt, mtdummy;
1294
1295         for (sm = opc->smatches; sm; sm=snext) {
1296                 snext = sm->sm_next;
1297                 syncprov_free_syncop( sm->sm_op );
1298                 op->o_tmpfree( sm, op->o_tmpmemctx );
1299         }
1300
1301         /* Remove op from lock table */
1302         mtdummy.mt_op = op;
1303         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1304         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1305         if ( mt ) {
1306                 modinst *mi = mt->mt_mods;
1307
1308                 /* If there are more, promote the next one */
1309                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1310                 if ( mi->mi_next ) {
1311                         mt->mt_mods = mi->mi_next;
1312                         mt->mt_op = mt->mt_mods->mi_op;
1313                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1314                 } else {
1315                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
1316                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1317                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1318                         ch_free( mt );
1319                 }
1320         }
1321         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1322         if ( !BER_BVISNULL( &opc->suuid ))
1323                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1324         if ( !BER_BVISNULL( &opc->sndn ))
1325                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1326         if ( !BER_BVISNULL( &opc->sdn ))
1327                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1328         op->o_callback = cb->sc_next;
1329         op->o_tmpfree(cb, op->o_tmpmemctx);
1330
1331         return 0;
1332 }
1333
1334 static void
1335 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1336 {
1337         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1338         Modifications mod;
1339         Operation opm;
1340         SlapReply rsm = { 0 };
1341         slap_callback cb = {0};
1342         BackendDB be;
1343 #ifdef CHECK_CSN
1344         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
1345
1346         int i;
1347         for ( i=0; i<si->si_numcsns; i++ ) {
1348                 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1349         }
1350 #endif
1351         mod.sml_numvals = si->si_numcsns;
1352         mod.sml_values = si->si_ctxcsn;
1353         mod.sml_nvalues = NULL;
1354         mod.sml_desc = slap_schema.si_ad_contextCSN;
1355         mod.sml_op = LDAP_MOD_REPLACE;
1356         mod.sml_flags = SLAP_MOD_INTERNAL;
1357         mod.sml_next = NULL;
1358
1359         cb.sc_response = slap_null_cb;
1360         opm = *op;
1361         opm.o_tag = LDAP_REQ_MODIFY;
1362         opm.o_callback = &cb;
1363         opm.orm_modlist = &mod;
1364         opm.orm_no_opattrs = 1;
1365         if ( SLAP_GLUE_SUBORDINATE( op->o_bd )) {
1366                 be = *on->on_info->oi_origdb;
1367                 opm.o_bd = &be;
1368         }
1369         opm.o_req_dn = opm.o_bd->be_suffix[0];
1370         opm.o_req_ndn = opm.o_bd->be_nsuffix[0];
1371         opm.o_bd->bd_info = on->on_info->oi_orig;
1372         opm.o_managedsait = SLAP_CONTROL_NONCRITICAL;
1373         opm.o_no_schema_check = 1;
1374         opm.o_bd->be_modify( &opm, &rsm );
1375         if ( mod.sml_next != NULL ) {
1376                 slap_mods_free( mod.sml_next, 1 );
1377         }
1378 #ifdef CHECK_CSN
1379         for ( i=0; i<si->si_numcsns; i++ ) {
1380                 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1381         }
1382 #endif
1383 }
1384
1385 static void
1386 syncprov_add_slog( Operation *op )
1387 {
1388         opcookie *opc = op->o_callback->sc_private;
1389         slap_overinst *on = opc->son;
1390         syncprov_info_t         *si = on->on_bi.bi_private;
1391         sessionlog *sl;
1392         slog_entry *se;
1393
1394         sl = si->si_logs;
1395         {
1396                 /* Allocate a record. UUIDs are not NUL-terminated. */
1397                 se = ch_malloc( sizeof( slog_entry ) + opc->suuid.bv_len + 
1398                         op->o_csn.bv_len + 1 );
1399                 se->se_next = NULL;
1400                 se->se_tag = op->o_tag;
1401
1402                 se->se_uuid.bv_val = (char *)(&se[1]);
1403                 AC_MEMCPY( se->se_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1404                 se->se_uuid.bv_len = opc->suuid.bv_len;
1405
1406                 se->se_csn.bv_val = se->se_uuid.bv_val + opc->suuid.bv_len;
1407                 AC_MEMCPY( se->se_csn.bv_val, op->o_csn.bv_val, op->o_csn.bv_len );
1408                 se->se_csn.bv_val[op->o_csn.bv_len] = '\0';
1409                 se->se_csn.bv_len = op->o_csn.bv_len;
1410                 se->se_sid = slap_parse_csn_sid( &se->se_csn );
1411
1412                 ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
1413                 if ( sl->sl_head ) {
1414                         sl->sl_tail->se_next = se;
1415                 } else {
1416                         sl->sl_head = se;
1417                 }
1418                 sl->sl_tail = se;
1419                 sl->sl_num++;
1420                 while ( sl->sl_num > sl->sl_size ) {
1421                         se = sl->sl_head;
1422                         sl->sl_head = se->se_next;
1423                         strcpy( sl->sl_mincsn.bv_val, se->se_csn.bv_val );
1424                         sl->sl_mincsn.bv_len = se->se_csn.bv_len;
1425                         ch_free( se );
1426                         sl->sl_num--;
1427                 }
1428                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1429         }
1430 }
1431
1432 /* Just set a flag if we found the matching entry */
1433 static int
1434 playlog_cb( Operation *op, SlapReply *rs )
1435 {
1436         if ( rs->sr_type == REP_SEARCH ) {
1437                 op->o_callback->sc_private = (void *)1;
1438         }
1439         return rs->sr_err;
1440 }
1441
1442 /* enter with sl->sl_mutex locked, release before returning */
1443 static void
1444 syncprov_playlog( Operation *op, SlapReply *rs, sessionlog *sl,
1445         sync_control *srs, BerVarray ctxcsn, int numcsns, int *sids )
1446 {
1447         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1448         slog_entry *se;
1449         int i, j, ndel, num, nmods, mmods;
1450         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1451         BerVarray uuids;
1452         struct berval delcsn[2];
1453
1454         if ( !sl->sl_num ) {
1455                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1456                 return;
1457         }
1458
1459         num = sl->sl_num;
1460         i = 0;
1461         nmods = 0;
1462
1463         uuids = op->o_tmpalloc( (num+1) * sizeof( struct berval ) +
1464                 num * UUID_LEN, op->o_tmpmemctx );
1465         uuids[0].bv_val = (char *)(uuids + num + 1);
1466
1467         delcsn[0].bv_len = 0;
1468         delcsn[0].bv_val = cbuf;
1469         BER_BVZERO(&delcsn[1]);
1470
1471         /* Make a copy of the relevant UUIDs. Put the Deletes up front
1472          * and everything else at the end. Do this first so we can
1473          * unlock the list mutex.
1474          */
1475         Debug( LDAP_DEBUG_SYNC, "srs csn %s\n",
1476                 srs->sr_state.ctxcsn[0].bv_val, 0, 0 );
1477         for ( se=sl->sl_head; se; se=se->se_next ) {
1478                 int k;
1479                 Debug( LDAP_DEBUG_SYNC, "log csn %s\n", se->se_csn.bv_val, 0, 0 );
1480                 ndel = 1;
1481                 for ( k=0; k<srs->sr_state.numcsns; k++ ) {
1482                         if ( se->se_sid == srs->sr_state.sids[k] ) {
1483                                 ndel = ber_bvcmp( &se->se_csn, &srs->sr_state.ctxcsn[k] );
1484                                 break;
1485                         }
1486                 }
1487                 if ( ndel <= 0 ) {
1488                         Debug( LDAP_DEBUG_SYNC, "cmp %d, too old\n", ndel, 0, 0 );
1489                         continue;
1490                 }
1491                 ndel = 0;
1492                 for ( k=0; k<numcsns; k++ ) {
1493                         if ( se->se_sid == sids[k] ) {
1494                                 ndel = ber_bvcmp( &se->se_csn, &ctxcsn[k] );
1495                                 break;
1496                         }
1497                 }
1498                 if ( ndel > 0 ) {
1499                         Debug( LDAP_DEBUG_SYNC, "cmp %d, too new\n", ndel, 0, 0 );
1500                         break;
1501                 }
1502                 if ( se->se_tag == LDAP_REQ_DELETE ) {
1503                         j = i;
1504                         i++;
1505                         AC_MEMCPY( cbuf, se->se_csn.bv_val, se->se_csn.bv_len );
1506                         delcsn[0].bv_len = se->se_csn.bv_len;
1507                         delcsn[0].bv_val[delcsn[0].bv_len] = '\0';
1508                 } else {
1509                         nmods++;
1510                         j = num - nmods;
1511                 }
1512                 uuids[j].bv_val = uuids[0].bv_val + (j * UUID_LEN);
1513                 AC_MEMCPY(uuids[j].bv_val, se->se_uuid.bv_val, UUID_LEN);
1514                 uuids[j].bv_len = UUID_LEN;
1515         }
1516         ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1517
1518         ndel = i;
1519
1520         /* Zero out unused slots */
1521         for ( i=ndel; i < num - nmods; i++ )
1522                 uuids[i].bv_len = 0;
1523
1524         /* Mods must be validated to see if they belong in this delete set.
1525          */
1526
1527         mmods = nmods;
1528         /* Strip any duplicates */
1529         for ( i=0; i<nmods; i++ ) {
1530                 for ( j=0; j<ndel; j++ ) {
1531                         if ( bvmatch( &uuids[j], &uuids[num - 1 - i] )) {
1532                                 uuids[num - 1 - i].bv_len = 0;
1533                                 mmods --;
1534                                 break;
1535                         }
1536                 }
1537                 if ( uuids[num - 1 - i].bv_len == 0 ) continue;
1538                 for ( j=0; j<i; j++ ) {
1539                         if ( bvmatch( &uuids[num - 1 - j], &uuids[num - 1 - i] )) {
1540                                 uuids[num - 1 - i].bv_len = 0;
1541                                 mmods --;
1542                                 break;
1543                         }
1544                 }
1545         }
1546
1547         if ( mmods ) {
1548                 Operation fop;
1549                 SlapReply frs = { REP_RESULT };
1550                 int rc;
1551                 Filter mf, af;
1552                 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
1553                 slap_callback cb = {0};
1554
1555                 fop = *op;
1556
1557                 fop.o_sync_mode = 0;
1558                 fop.o_callback = &cb;
1559                 fop.ors_limit = NULL;
1560                 fop.ors_tlimit = SLAP_NO_LIMIT;
1561                 fop.ors_attrs = slap_anlist_all_attributes;
1562                 fop.ors_attrsonly = 0;
1563                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
1564
1565                 af.f_choice = LDAP_FILTER_AND;
1566                 af.f_next = NULL;
1567                 af.f_and = &mf;
1568                 mf.f_choice = LDAP_FILTER_EQUALITY;
1569                 mf.f_ava = &eq;
1570                 mf.f_av_desc = slap_schema.si_ad_entryUUID;
1571                 mf.f_next = fop.ors_filter;
1572
1573                 fop.ors_filter = &af;
1574
1575                 cb.sc_response = playlog_cb;
1576                 fop.o_bd->bd_info = (BackendInfo *)on->on_info;
1577
1578                 for ( i=ndel; i<num; i++ ) {
1579                         if ( uuids[i].bv_len == 0 ) continue;
1580
1581                         mf.f_av_value = uuids[i];
1582                         cb.sc_private = NULL;
1583                         fop.ors_slimit = 1;
1584                         frs.sr_nentries = 0;
1585                         rc = fop.o_bd->be_search( &fop, &frs );
1586
1587                         /* If entry was not found, add to delete list */
1588                         if ( !cb.sc_private ) {
1589                                 uuids[ndel++] = uuids[i];
1590                         }
1591                 }
1592                 fop.o_bd->bd_info = (BackendInfo *)on;
1593         }
1594         if ( ndel ) {
1595                 struct berval cookie;
1596
1597                 if ( delcsn[0].bv_len ) {
1598                         slap_compose_sync_cookie( op, &cookie, delcsn, srs->sr_state.rid,
1599                                 slap_serverID ? slap_serverID : -1 );
1600
1601                         Debug( LDAP_DEBUG_SYNC, "syncprov_playlog: cookie=%s\n", cookie.bv_val, 0, 0 );
1602                 }
1603
1604                 uuids[ndel].bv_val = NULL;
1605                 syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET,
1606                         delcsn[0].bv_len ? &cookie : NULL, 0, uuids, 1 );
1607                 if ( delcsn[0].bv_len ) {
1608                         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
1609                 }
1610         }
1611         op->o_tmpfree( uuids, op->o_tmpmemctx );
1612 }
1613
1614 static int
1615 syncprov_op_response( Operation *op, SlapReply *rs )
1616 {
1617         opcookie *opc = op->o_callback->sc_private;
1618         slap_overinst *on = opc->son;
1619         syncprov_info_t         *si = on->on_bi.bi_private;
1620         syncmatches *sm;
1621
1622         if ( rs->sr_err == LDAP_SUCCESS )
1623         {
1624                 struct berval maxcsn;
1625                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1626                 int do_check = 0, have_psearches, foundit, csn_changed = 0;
1627
1628                 /* Update our context CSN */
1629                 cbuf[0] = '\0';
1630                 maxcsn.bv_val = cbuf;
1631                 maxcsn.bv_len = sizeof(cbuf);
1632                 ldap_pvt_thread_rdwr_wlock( &si->si_csn_rwlock );
1633
1634 #if 0
1635                 if ( op->o_dont_replicate &&
1636                                 op->orm_modlist->sml_op == LDAP_MOD_REPLACE &&
1637                                 op->orm_modlist->sml_desc == slap_schema.si_ad_contextCSN ) {
1638                         /* Catch contextCSN updates from syncrepl. We have to look at
1639                          * all the attribute values, as there may be more than one csn
1640                          * that changed, and only one can be passed in the csn queue.
1641                          */
1642                         Modifications *mod = op->orm_modlist;
1643                         int i, j, sid;
1644
1645                         for ( i=0; i<mod->sml_numvals; i++ ) {
1646                                 sid = slap_parse_csn_sid( &mod->sml_values[i] );
1647
1648                                 for ( j=0; j<si->si_numcsns; j++ ) {
1649                                         if ( sid == si->si_sids[j] ) {
1650                                                 if ( ber_bvcmp( &mod->sml_values[i], &si->si_ctxcsn[j] ) > 0 ) {
1651                                                         ber_bvreplace( &si->si_ctxcsn[j], &mod->sml_values[i] );
1652                                                         csn_changed = 1;
1653                                                 }
1654                                                 break;
1655                                         }
1656                                 }
1657
1658                                 if ( j == si->si_numcsns ) {
1659                                         value_add_one( &si->si_ctxcsn, &mod->sml_values[i] );
1660                                         si->si_numcsns++;
1661                                         si->si_sids = ch_realloc( si->si_sids, si->si_numcsns *
1662                                                 sizeof(int));
1663                                         si->si_sids[j] = sid;
1664                                         csn_changed = 1;
1665                                 }
1666                         }
1667                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1668
1669                         if ( csn_changed ) {
1670                                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1671                                 have_psearches = ( si->si_ops != NULL );
1672                                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1673
1674                                 if ( have_psearches ) {
1675                                         for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1676                                                 if ( sm->sm_op->s_op->o_abandon )
1677                                                         continue;
1678                                                 syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_NEW_COOKIE );
1679                                         }
1680                                 }
1681                         }
1682                         return SLAP_CB_CONTINUE;
1683                 }
1684 #endif
1685
1686                 slap_get_commit_csn( op, &maxcsn, &foundit );
1687                 if ( BER_BVISEMPTY( &maxcsn ) && SLAP_GLUE_SUBORDINATE( op->o_bd )) {
1688                         /* syncrepl queues the CSN values in the db where
1689                          * it is configured , not where the changes are made.
1690                          * So look for a value in the glue db if we didn't
1691                          * find any in this db.
1692                          */
1693                         BackendDB *be = op->o_bd;
1694                         op->o_bd = select_backend( &be->be_nsuffix[0], 1);
1695                         maxcsn.bv_val = cbuf;
1696                         maxcsn.bv_len = sizeof(cbuf);
1697                         slap_get_commit_csn( op, &maxcsn, &foundit );
1698                         op->o_bd = be;
1699                 }
1700                 if ( !BER_BVISEMPTY( &maxcsn ) ) {
1701                         int i, sid;
1702 #ifdef CHECK_CSN
1703                         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
1704                         assert( !syn->ssyn_validate( syn, &maxcsn ));
1705 #endif
1706                         sid = slap_parse_csn_sid( &maxcsn );
1707                         for ( i=0; i<si->si_numcsns; i++ ) {
1708                                 if ( sid == si->si_sids[i] ) {
1709                                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn[i] ) > 0 ) {
1710                                                 ber_bvreplace( &si->si_ctxcsn[i], &maxcsn );
1711                                                 csn_changed = 1;
1712                                         }
1713                                         break;
1714                                 }
1715                         }
1716                         /* It's a new SID for us */
1717                         if ( i == si->si_numcsns ) {
1718                                 value_add_one( &si->si_ctxcsn, &maxcsn );
1719                                 csn_changed = 1;
1720                                 si->si_numcsns++;
1721                                 si->si_sids = ch_realloc( si->si_sids, si->si_numcsns *
1722                                         sizeof(int));
1723                                 si->si_sids[i] = sid;
1724                         }
1725                 } else if ( !foundit ) {
1726                         /* internal ops that aren't meant to be replicated */
1727                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1728                         return SLAP_CB_CONTINUE;
1729                 }
1730
1731                 /* Don't do any processing for consumer contextCSN updates */
1732                 if ( op->o_dont_replicate ) {
1733                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1734                         return SLAP_CB_CONTINUE;
1735                 }
1736
1737                 si->si_numops++;
1738                 if ( si->si_chkops || si->si_chktime ) {
1739                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1740                                 do_check = 1;
1741                                 si->si_numops = 0;
1742                         }
1743                         if ( si->si_chktime &&
1744                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1745                                 if ( si->si_chklast ) {
1746                                         do_check = 1;
1747                                         si->si_chklast = op->o_time;
1748                                 } else {
1749                                         si->si_chklast = 1;
1750                                 }
1751                         }
1752                 }
1753                 ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1754
1755                 if ( do_check ) {
1756                         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
1757                         syncprov_checkpoint( op, rs, on );
1758                         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
1759                 }
1760
1761                 /* only update consumer ctx if this is a newer csn */
1762                 if ( csn_changed ) {
1763                         opc->sctxcsn = maxcsn;
1764                 }
1765
1766                 /* Handle any persistent searches */
1767                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1768                 have_psearches = ( si->si_ops != NULL );
1769                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1770                 if ( have_psearches ) {
1771                         switch(op->o_tag) {
1772                         case LDAP_REQ_ADD:
1773                         case LDAP_REQ_MODIFY:
1774                         case LDAP_REQ_MODRDN:
1775                         case LDAP_REQ_EXTENDED:
1776                                 syncprov_matchops( op, opc, 0 );
1777                                 break;
1778                         case LDAP_REQ_DELETE:
1779                                 /* for each match in opc->smatches:
1780                                  *   send DELETE msg
1781                                  */
1782                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1783                                         if ( sm->sm_op->s_op->o_abandon )
1784                                                 continue;
1785                                         syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_DELETE );
1786                                 }
1787                                 break;
1788                         }
1789                 }
1790
1791                 /* Add any log records */
1792                 if ( si->si_logs && op->o_tag != LDAP_REQ_ADD ) {
1793                         syncprov_add_slog( op );
1794                 }
1795
1796         }
1797         return SLAP_CB_CONTINUE;
1798 }
1799
1800 /* We don't use a subentry to store the context CSN any more.
1801  * We expose the current context CSN as an operational attribute
1802  * of the suffix entry.
1803  */
1804 static int
1805 syncprov_op_compare( Operation *op, SlapReply *rs )
1806 {
1807         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1808         syncprov_info_t         *si = on->on_bi.bi_private;
1809         int rc = SLAP_CB_CONTINUE;
1810
1811         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1812                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1813         {
1814                 Entry e = {0};
1815                 Attribute a = {0};
1816
1817                 e.e_name = op->o_bd->be_suffix[0];
1818                 e.e_nname = op->o_bd->be_nsuffix[0];
1819                 e.e_attrs = &a;
1820
1821                 a.a_desc = slap_schema.si_ad_contextCSN;
1822
1823                 ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
1824
1825                 a.a_vals = si->si_ctxcsn;
1826                 a.a_nvals = a.a_vals;
1827                 a.a_numvals = si->si_numcsns;
1828
1829                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1830                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1831                 if ( ! rs->sr_err ) {
1832                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1833                         goto return_results;
1834                 }
1835
1836                 if ( get_assert( op ) &&
1837                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1838                 {
1839                         rs->sr_err = LDAP_ASSERTION_FAILED;
1840                         goto return_results;
1841                 }
1842
1843
1844                 rs->sr_err = LDAP_COMPARE_FALSE;
1845
1846                 if ( attr_valfind( &a,
1847                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1848                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1849                                 &op->oq_compare.rs_ava->aa_value, NULL, op->o_tmpmemctx ) == 0 )
1850                 {
1851                         rs->sr_err = LDAP_COMPARE_TRUE;
1852                 }
1853
1854 return_results:;
1855
1856                 ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
1857
1858                 send_ldap_result( op, rs );
1859
1860                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1861                         rs->sr_err = LDAP_SUCCESS;
1862                 }
1863                 rc = rs->sr_err;
1864         }
1865
1866         return rc;
1867 }
1868
1869 static int
1870 syncprov_op_mod( Operation *op, SlapReply *rs )
1871 {
1872         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1873         syncprov_info_t         *si = on->on_bi.bi_private;
1874         slap_callback *cb;
1875         opcookie *opc;
1876         int have_psearches, cbsize;
1877
1878         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1879         have_psearches = ( si->si_ops != NULL );
1880         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1881
1882         cbsize = sizeof(slap_callback) + sizeof(opcookie) +
1883                 (have_psearches ? sizeof(modinst) : 0 );
1884
1885         cb = op->o_tmpcalloc(1, cbsize, op->o_tmpmemctx);
1886         opc = (opcookie *)(cb+1);
1887         opc->son = on;
1888         cb->sc_response = syncprov_op_response;
1889         cb->sc_cleanup = syncprov_op_cleanup;
1890         cb->sc_private = opc;
1891         cb->sc_next = op->o_callback;
1892         op->o_callback = cb;
1893
1894         if ( op->o_csn.bv_val ) {
1895                 opc->ssid = slap_parse_csn_sid( &op->o_csn );
1896         } else {
1897                 opc->ssid = -1;
1898         }
1899
1900         /* If there are active persistent searches, lock this operation.
1901          * See seqmod.c for the locking logic on its own.
1902          */
1903         if ( have_psearches ) {
1904                 modtarget *mt, mtdummy;
1905                 modinst *mi;
1906
1907                 mi = (modinst *)(opc+1);
1908                 mi->mi_op = op;
1909
1910                 /* See if we're already modifying this entry... */
1911                 mtdummy.mt_op = op;
1912                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1913                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1914                 if ( mt ) {
1915                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1916                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1917                         mt->mt_tail->mi_next = mi;
1918                         mt->mt_tail = mi;
1919                         /* wait for this op to get to head of list */
1920                         while ( mt->mt_mods != mi ) {
1921                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1922                                 /* FIXME: if dynamic config can delete overlays or
1923                                  * databases we'll have to check for cleanup here.
1924                                  * Currently it's not an issue because there are
1925                                  * no dynamic config deletes...
1926                                  */
1927                                 if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1928                                         ldap_pvt_thread_yield();
1929                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1930
1931                                 /* clean up if the caller is giving up */
1932                                 if ( op->o_abandon ) {
1933                                         modinst *m2;
1934                                         for ( m2 = mt->mt_mods; m2->mi_next != mi;
1935                                                 m2 = m2->mi_next );
1936                                         m2->mi_next = mi->mi_next;
1937                                         if ( mt->mt_tail == mi ) mt->mt_tail = m2;
1938                                         op->o_tmpfree( cb, op->o_tmpmemctx );
1939                                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1940                                         return SLAPD_ABANDON;
1941                                 }
1942                         }
1943                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1944                 } else {
1945                         /* Record that we're modifying this entry now */
1946                         mt = ch_malloc( sizeof(modtarget) );
1947                         mt->mt_mods = mi;
1948                         mt->mt_tail = mi;
1949                         mt->mt_op = mi->mi_op;
1950                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1951                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1952                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1953                 }
1954         }
1955
1956         if (( have_psearches || si->si_logs ) && op->o_tag != LDAP_REQ_ADD )
1957                 syncprov_matchops( op, opc, 1 );
1958
1959         return SLAP_CB_CONTINUE;
1960 }
1961
1962 static int
1963 syncprov_op_extended( Operation *op, SlapReply *rs )
1964 {
1965         if ( exop_is_write( op ))
1966                 return syncprov_op_mod( op, rs );
1967
1968         return SLAP_CB_CONTINUE;
1969 }
1970
1971 typedef struct searchstate {
1972         slap_overinst *ss_on;
1973         syncops *ss_so;
1974         BerVarray ss_ctxcsn;
1975         int *ss_sids;
1976         int ss_numcsns;
1977 #define SS_PRESENT      0x01
1978 #define SS_CHANGED      0x02
1979         int ss_flags;
1980 } searchstate;
1981
1982 static int
1983 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1984 {
1985         if ( rs->sr_ctrls ) {
1986                 op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
1987                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1988                 rs->sr_ctrls = NULL;
1989         }
1990         return 0;
1991 }
1992
1993 typedef struct SyncOperationBuffer {
1994         Operation               sob_op;
1995         Opheader                sob_hdr;
1996         OpExtra                 sob_oe;
1997         AttributeName   sob_extra;      /* not always present */
1998         /* Further data allocated here */
1999 } SyncOperationBuffer;
2000
2001 static void
2002 syncprov_detach_op( Operation *op, syncops *so, slap_overinst *on )
2003 {
2004         SyncOperationBuffer *sopbuf2;
2005         Operation *op2;
2006         int i, alen = 0;
2007         size_t size;
2008         char *ptr;
2009         GroupAssertion *g1, *g2;
2010
2011         /* count the search attrs */
2012         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2013                 alen += op->ors_attrs[i].an_name.bv_len + 1;
2014         }
2015         /* Make a new copy of the operation */
2016         size = offsetof( SyncOperationBuffer, sob_extra ) +
2017                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
2018                 op->o_req_dn.bv_len + 1 +
2019                 op->o_req_ndn.bv_len + 1 +
2020                 op->o_ndn.bv_len + 1 +
2021                 so->s_filterstr.bv_len + 1;
2022         sopbuf2 = ch_calloc( 1, size );
2023         op2 = &sopbuf2->sob_op;
2024         op2->o_hdr = &sopbuf2->sob_hdr;
2025         LDAP_SLIST_FIRST(&op2->o_extra) = &sopbuf2->sob_oe;
2026
2027         /* Copy the fields we care about explicitly, leave the rest alone */
2028         *op2->o_hdr = *op->o_hdr;
2029         op2->o_tag = op->o_tag;
2030         op2->o_time = op->o_time;
2031         op2->o_bd = on->on_info->oi_origdb;
2032         op2->o_request = op->o_request;
2033         op2->o_managedsait = op->o_managedsait;
2034         LDAP_SLIST_FIRST(&op2->o_extra)->oe_key = on;
2035         LDAP_SLIST_NEXT(LDAP_SLIST_FIRST(&op2->o_extra), oe_next) = NULL;
2036
2037         ptr = (char *) sopbuf2 + offsetof( SyncOperationBuffer, sob_extra );
2038         if ( i ) {
2039                 op2->ors_attrs = (AttributeName *) ptr;
2040                 ptr = (char *) &op2->ors_attrs[i+1];
2041                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2042                         op2->ors_attrs[i] = op->ors_attrs[i];
2043                         op2->ors_attrs[i].an_name.bv_val = ptr;
2044                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
2045                 }
2046                 BER_BVZERO( &op2->ors_attrs[i].an_name );
2047         }
2048
2049         op2->o_authz = op->o_authz;
2050         op2->o_ndn.bv_val = ptr;
2051         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
2052         op2->o_dn = op2->o_ndn;
2053         op2->o_req_dn.bv_len = op->o_req_dn.bv_len;
2054         op2->o_req_dn.bv_val = ptr;
2055         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
2056         op2->o_req_ndn.bv_len = op->o_req_ndn.bv_len;
2057         op2->o_req_ndn.bv_val = ptr;
2058         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
2059         op2->ors_filterstr.bv_val = ptr;
2060         strcpy( ptr, so->s_filterstr.bv_val );
2061         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
2062
2063         /* Skip the AND/GE clause that we stuck on in front */
2064         if ( so->s_flags & PS_FIX_FILTER ) {
2065                 op2->ors_filter = op->ors_filter->f_and->f_next;
2066                 so->s_flags ^= PS_FIX_FILTER;
2067         } else {
2068                 op2->ors_filter = op->ors_filter;
2069         }
2070         op2->ors_filter = filter_dup( op2->ors_filter, NULL );
2071         so->s_op = op2;
2072
2073         /* Copy any cached group ACLs individually */
2074         op2->o_groups = NULL;
2075         for ( g1=op->o_groups; g1; g1=g1->ga_next ) {
2076                 g2 = ch_malloc( sizeof(GroupAssertion) + g1->ga_len );
2077                 *g2 = *g1;
2078                 strcpy( g2->ga_ndn, g1->ga_ndn );
2079                 g2->ga_next = op2->o_groups;
2080                 op2->o_groups = g2;
2081         }
2082         /* Don't allow any further group caching */
2083         op2->o_do_not_cache = 1;
2084
2085         /* Add op2 to conn so abandon will find us */
2086         op->o_conn->c_n_ops_executing++;
2087         op->o_conn->c_n_ops_completed--;
2088         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op2, o_next );
2089         so->s_flags |= PS_IS_DETACHED;
2090
2091         /* Prevent anyone else from trying to send a result for this op */
2092         op->o_abandon = 1;
2093 }
2094
2095 static int
2096 syncprov_search_response( Operation *op, SlapReply *rs )
2097 {
2098         searchstate *ss = op->o_callback->sc_private;
2099         slap_overinst *on = ss->ss_on;
2100         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2101         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
2102
2103         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
2104                 Attribute *a;
2105                 /* If we got a referral without a referral object, there's
2106                  * something missing that we cannot replicate. Just ignore it.
2107                  * The consumer will abort because we didn't send the expected
2108                  * control.
2109                  */
2110                 if ( !rs->sr_entry ) {
2111                         assert( rs->sr_entry != NULL );
2112                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
2113                         return SLAP_CB_CONTINUE;
2114                 }
2115                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryCSN );
2116                 if ( a == NULL && rs->sr_operational_attrs != NULL ) {
2117                         a = attr_find( rs->sr_operational_attrs, slap_schema.si_ad_entryCSN );
2118                 }
2119                 if ( a ) {
2120                         int i, sid;
2121                         sid = slap_parse_csn_sid( &a->a_nvals[0] );
2122
2123                         /* Don't send changed entries back to the originator */
2124                         if ( sid == srs->sr_state.sid && srs->sr_state.numcsns ) {
2125                                 Debug( LDAP_DEBUG_SYNC,
2126                                         "Entry %s changed by peer, ignored\n",
2127                                         rs->sr_entry->e_name.bv_val, 0, 0 );
2128                                 return LDAP_SUCCESS;
2129                         }
2130
2131                         /* If not a persistent search */
2132                         if ( !ss->ss_so ) {
2133                                 /* Make sure entry is less than the snapshot'd contextCSN */
2134                                 for ( i=0; i<ss->ss_numcsns; i++ ) {
2135                                         if ( sid == ss->ss_sids[i] && ber_bvcmp( &a->a_nvals[0],
2136                                                 &ss->ss_ctxcsn[i] ) > 0 ) {
2137                                                 Debug( LDAP_DEBUG_SYNC,
2138                                                         "Entry %s CSN %s greater than snapshot %s\n",
2139                                                         rs->sr_entry->e_name.bv_val,
2140                                                         a->a_nvals[0].bv_val,
2141                                                         ss->ss_ctxcsn[i].bv_val );
2142                                                 return LDAP_SUCCESS;
2143                                         }
2144                                 }
2145                         }
2146
2147                         /* Don't send old entries twice */
2148                         if ( srs->sr_state.ctxcsn ) {
2149                                 for ( i=0; i<srs->sr_state.numcsns; i++ ) {
2150                                         if ( sid == srs->sr_state.sids[i] &&
2151                                                 ber_bvcmp( &a->a_nvals[0],
2152                                                         &srs->sr_state.ctxcsn[i] )<= 0 ) {
2153                                                 Debug( LDAP_DEBUG_SYNC,
2154                                                         "Entry %s CSN %s older or equal to ctx %s\n",
2155                                                         rs->sr_entry->e_name.bv_val,
2156                                                         a->a_nvals[0].bv_val,
2157                                                         srs->sr_state.ctxcsn[i].bv_val );
2158                                                 return LDAP_SUCCESS;
2159                                         }
2160                                 }
2161                         }
2162                 }
2163                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
2164                         op->o_tmpmemctx );
2165                 rs->sr_ctrls[1] = NULL;
2166                 /* If we're in delta-sync mode, always send a cookie */
2167                 if ( si->si_nopres && si->si_usehint && a ) {
2168                         struct berval cookie;
2169                         slap_compose_sync_cookie( op, &cookie, a->a_nvals, srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
2170                         rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
2171                                 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 1, &cookie );
2172                 } else {
2173                         rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
2174                                 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
2175                 }
2176         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
2177                 struct berval cookie;
2178
2179                 if ( ss->ss_flags & SS_CHANGED ) {
2180                         slap_compose_sync_cookie( op, &cookie, ss->ss_ctxcsn,
2181                                 srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
2182
2183                         Debug( LDAP_DEBUG_SYNC, "syncprov_search_response: cookie=%s\n", cookie.bv_val, 0, 0 );
2184                 }
2185
2186                 /* Is this a regular refresh?
2187                  * Note: refresh never gets here if there were no changes
2188                  */
2189                 if ( !ss->ss_so ) {
2190                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
2191                                 op->o_tmpmemctx );
2192                         rs->sr_ctrls[1] = NULL;
2193                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
2194                                 0, 1, &cookie, ( ss->ss_flags & SS_PRESENT ) ?  LDAP_SYNC_REFRESH_PRESENTS :
2195                                         LDAP_SYNC_REFRESH_DELETES );
2196                         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
2197                 } else {
2198                 /* It's RefreshAndPersist, transition to Persist phase */
2199                         syncprov_sendinfo( op, rs, ( ss->ss_flags & SS_PRESENT ) ?
2200                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
2201                                 ( ss->ss_flags & SS_CHANGED ) ? &cookie : NULL,
2202                                 1, NULL, 0 );
2203                         if ( ss->ss_flags & SS_CHANGED )
2204                                 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
2205
2206                         /* Detach this Op from frontend control */
2207                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
2208
2209                         /* But not if this connection was closed along the way */
2210                         if ( op->o_abandon ) {
2211                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
2212                                 /* syncprov_ab_cleanup will free this syncop */
2213                                 return SLAPD_ABANDON;
2214
2215                         } else {
2216                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
2217                                 /* Turn off the refreshing flag */
2218                                 ss->ss_so->s_flags ^= PS_IS_REFRESHING;
2219
2220                                 syncprov_detach_op( op, ss->ss_so, on );
2221
2222                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
2223
2224                                 /* If there are queued responses, fire them off */
2225                                 if ( ss->ss_so->s_res )
2226                                         syncprov_qstart( ss->ss_so );
2227                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
2228                         }
2229
2230                         return LDAP_SUCCESS;
2231                 }
2232         }
2233
2234         return SLAP_CB_CONTINUE;
2235 }
2236
2237 static int
2238 syncprov_op_search( Operation *op, SlapReply *rs )
2239 {
2240         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
2241         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2242         slap_callback   *cb;
2243         int gotstate = 0, changed = 0, do_present = 0;
2244         syncops *sop = NULL;
2245         searchstate *ss;
2246         sync_control *srs;
2247         BerVarray ctxcsn;
2248         int i, *sids, numcsns;
2249         struct berval mincsn;
2250
2251         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
2252
2253         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
2254                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
2255                 return rs->sr_err;
2256         }
2257
2258         srs = op->o_controls[slap_cids.sc_LDAPsync];
2259
2260         /* If this is a persistent search, set it up right away */
2261         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
2262                 syncops so = {0};
2263                 fbase_cookie fc;
2264                 opcookie opc;
2265                 slap_callback sc;
2266
2267                 fc.fss = &so;
2268                 fc.fbase = 0;
2269                 so.s_eid = NOID;
2270                 so.s_op = op;
2271                 so.s_flags = PS_IS_REFRESHING | PS_FIND_BASE;
2272                 /* syncprov_findbase expects to be called as a callback... */
2273                 sc.sc_private = &opc;
2274                 opc.son = on;
2275                 ldap_pvt_thread_mutex_init( &so.s_mutex );
2276                 cb = op->o_callback;
2277                 op->o_callback = &sc;
2278                 rs->sr_err = syncprov_findbase( op, &fc );
2279                 op->o_callback = cb;
2280                 ldap_pvt_thread_mutex_destroy( &so.s_mutex );
2281
2282                 if ( rs->sr_err != LDAP_SUCCESS ) {
2283                         send_ldap_result( op, rs );
2284                         return rs->sr_err;
2285                 }
2286                 sop = ch_malloc( sizeof( syncops ));
2287                 *sop = so;
2288                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
2289                 sop->s_rid = srs->sr_state.rid;
2290                 sop->s_sid = srs->sr_state.sid;
2291                 sop->s_inuse = 1;
2292
2293                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
2294                 sop->s_next = si->si_ops;
2295                 si->si_ops = sop;
2296                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
2297         }
2298
2299         /* snapshot the ctxcsn */
2300         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2301         numcsns = si->si_numcsns;
2302         if ( numcsns ) {
2303                 ber_bvarray_dup_x( &ctxcsn, si->si_ctxcsn, op->o_tmpmemctx );
2304                 sids = op->o_tmpalloc( numcsns * sizeof(int), op->o_tmpmemctx );
2305                 for ( i=0; i<numcsns; i++ )
2306                         sids[i] = si->si_sids[i];
2307         } else {
2308                 ctxcsn = NULL;
2309                 sids = NULL;
2310         }
2311         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2312         
2313         /* If we have a cookie, handle the PRESENT lookups */
2314         if ( srs->sr_state.ctxcsn ) {
2315                 sessionlog *sl;
2316                 int i, j;
2317
2318                 /* If we don't have any CSN of our own yet, pretend nothing
2319                  * has changed.
2320                  */
2321                 if ( !numcsns )
2322                         goto no_change;
2323
2324                 if ( !si->si_nopres )
2325                         do_present = SS_PRESENT;
2326
2327                 /* If there are SIDs we don't recognize in the cookie, drop them */
2328                 for (i=0; i<srs->sr_state.numcsns; ) {
2329                         for (j=0; j<numcsns; j++) {
2330                                 if ( srs->sr_state.sids[i] == sids[j] ) {
2331                                         break;
2332                                 }
2333                         }
2334                         /* not found */
2335                         if ( j == numcsns ) {
2336                                 struct berval tmp = srs->sr_state.ctxcsn[i];
2337                                 j = srs->sr_state.numcsns - 1;
2338                                 srs->sr_state.ctxcsn[i] = srs->sr_state.ctxcsn[j];
2339                                 tmp.bv_len = 0;
2340                                 srs->sr_state.ctxcsn[j] = tmp;
2341                                 srs->sr_state.numcsns = j;
2342                                 srs->sr_state.sids[i] = srs->sr_state.sids[j];
2343                                 continue;
2344                         }
2345                         i++;
2346                 }
2347
2348                 /* Find the smallest CSN */
2349                 mincsn = srs->sr_state.ctxcsn[0];
2350                 for ( i=1; i<srs->sr_state.numcsns; i++ ) {
2351                         if ( ber_bvcmp( &mincsn, &srs->sr_state.ctxcsn[i] ) > 0 )
2352                                 mincsn = srs->sr_state.ctxcsn[i];
2353                 }
2354
2355                 /* If nothing has changed, shortcut it */
2356                 if ( srs->sr_state.numcsns == numcsns ) {
2357                         int i, j;
2358                         for ( i=0; i<srs->sr_state.numcsns; i++ ) {
2359                                 for ( j=0; j<numcsns; j++ ) {
2360                                         if ( srs->sr_state.sids[i] != sids[j] )
2361                                                 continue;
2362                                         if ( !bvmatch( &srs->sr_state.ctxcsn[i], &ctxcsn[j] ))
2363                                                 changed = SS_CHANGED;
2364                                         break;
2365                                 }
2366                                 if ( changed )
2367                                         break;
2368                         }
2369                         if ( !changed ) {
2370                                 do_present = 0;
2371 no_change:              if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
2372                                         LDAPControl     *ctrls[2];
2373
2374                                         ctrls[0] = NULL;
2375                                         ctrls[1] = NULL;
2376                                         syncprov_done_ctrl( op, rs, ctrls, 0, 0,
2377                                                 NULL, LDAP_SYNC_REFRESH_DELETES );
2378                                         rs->sr_ctrls = ctrls;
2379                                         rs->sr_err = LDAP_SUCCESS;
2380                                         send_ldap_result( op, rs );
2381                                         rs->sr_ctrls = NULL;
2382                                         return rs->sr_err;
2383                                 }
2384                                 goto shortcut;
2385                         }
2386                 } else {
2387                         /* consumer doesn't have the right number of CSNs */
2388                         changed = SS_CHANGED;
2389                 }
2390                 /* Do we have a sessionlog for this search? */
2391                 sl=si->si_logs;
2392                 if ( sl ) {
2393                         ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
2394                         /* Are there any log entries, and is the consumer state
2395                          * present in the session log?
2396                          */
2397                         if ( sl->sl_num > 0 && ber_bvcmp( &mincsn, &sl->sl_mincsn ) >= 0 ) {
2398                                 do_present = 0;
2399                                 /* mutex is unlocked in playlog */
2400                                 syncprov_playlog( op, rs, sl, srs, ctxcsn, numcsns, sids );
2401                         } else {
2402                                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
2403                         }
2404                 }
2405                 /* Is the CSN still present in the database? */
2406                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
2407                         /* No, so a reload is required */
2408                         /* the 2.2 consumer doesn't send this hint */
2409                         if ( si->si_usehint && srs->sr_rhint == 0 ) {
2410                                 if ( ctxcsn )
2411                                         ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
2412                                 if ( sids )
2413                                         op->o_tmpfree( sids, op->o_tmpmemctx );
2414                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
2415                                 return rs->sr_err;
2416                         }
2417                         if ( srs->sr_state.ctxcsn ) {
2418                                 ber_bvarray_free_x( srs->sr_state.ctxcsn, op->o_tmpmemctx );
2419                                 srs->sr_state.ctxcsn = NULL;
2420                         }
2421                         if ( srs->sr_state.sids ) {
2422                                 slap_sl_free( srs->sr_state.sids, op->o_tmpmemctx );
2423                                 srs->sr_state.sids = NULL;
2424                         }
2425                         srs->sr_state.numcsns = 0;
2426                 } else {
2427                         gotstate = 1;
2428                         /* If changed and doing Present lookup, send Present UUIDs */
2429                         if ( do_present && syncprov_findcsn( op, FIND_PRESENT ) !=
2430                                 LDAP_SUCCESS ) {
2431                                 if ( ctxcsn )
2432                                         ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
2433                                 if ( sids )
2434                                         op->o_tmpfree( sids, op->o_tmpmemctx );
2435                                 send_ldap_result( op, rs );
2436                                 return rs->sr_err;
2437                         }
2438                 }
2439         } else {
2440                 /* No consumer state, assume something has changed */
2441                 changed = SS_CHANGED;
2442         }
2443
2444 shortcut:
2445         /* Append CSN range to search filter, save original filter
2446          * for persistent search evaluation
2447          */
2448         if ( sop ) {
2449                 sop->s_filterstr= op->ors_filterstr;
2450         }
2451
2452         /* If something changed, find the changes */
2453         if ( gotstate && changed ) {
2454                 Filter *fand, *fava;
2455
2456                 fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
2457                 fand->f_choice = LDAP_FILTER_AND;
2458                 fand->f_next = NULL;
2459                 fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
2460                 fand->f_and = fava;
2461                 fava->f_choice = LDAP_FILTER_GE;
2462                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
2463                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
2464 #ifdef LDAP_COMP_MATCH
2465                 fava->f_ava->aa_cf = NULL;
2466 #endif
2467                 ber_dupbv_x( &fava->f_ava->aa_value, &mincsn, op->o_tmpmemctx );
2468                 fava->f_next = op->ors_filter;
2469                 op->ors_filter = fand;
2470                 filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2471                 if ( sop )
2472                         sop->s_flags |= PS_FIX_FILTER;
2473         }
2474
2475         /* Let our callback add needed info to returned entries */
2476         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
2477         ss = (searchstate *)(cb+1);
2478         ss->ss_on = on;
2479         ss->ss_so = sop;
2480         ss->ss_flags = do_present | changed;
2481         ss->ss_ctxcsn = ctxcsn;
2482         ss->ss_numcsns = numcsns;
2483         ss->ss_sids = sids;
2484         cb->sc_response = syncprov_search_response;
2485         cb->sc_cleanup = syncprov_search_cleanup;
2486         cb->sc_private = ss;
2487         cb->sc_next = op->o_callback;
2488         op->o_callback = cb;
2489
2490         /* If this is a persistent search and no changes were reported during
2491          * the refresh phase, just invoke the response callback to transition
2492          * us into persist phase
2493          */
2494         if ( !changed ) {
2495                 rs->sr_err = LDAP_SUCCESS;
2496                 rs->sr_nentries = 0;
2497                 send_ldap_result( op, rs );
2498                 return rs->sr_err;
2499         }
2500         return SLAP_CB_CONTINUE;
2501 }
2502
2503 static int
2504 syncprov_operational(
2505         Operation *op,
2506         SlapReply *rs )
2507 {
2508         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
2509         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2510
2511         /* This prevents generating unnecessarily; frontend will strip
2512          * any statically stored copy.
2513          */
2514         if ( op->o_sync != SLAP_CONTROL_NONE )
2515                 return SLAP_CB_CONTINUE;
2516
2517         if ( rs->sr_entry &&
2518                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
2519
2520                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
2521                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
2522                         Attribute *a, **ap = NULL;
2523
2524                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
2525                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
2526                                         break;
2527                         }
2528
2529                         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2530                         if ( si->si_ctxcsn ) {
2531                                 if ( !a ) {
2532                                         for ( ap = &rs->sr_operational_attrs; *ap;
2533                                                 ap=&(*ap)->a_next );
2534
2535                                         a = attr_alloc( slap_schema.si_ad_contextCSN );
2536                                         *ap = a;
2537                                 }
2538
2539                                 if ( !ap ) {
2540                                         if ( !(rs->sr_flags & REP_ENTRY_MODIFIABLE) ) {
2541                                                 Entry *e = entry_dup( rs->sr_entry );
2542                                                 if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
2543                                                         overlay_entry_release_ov( op, rs->sr_entry, 0, on );
2544                                                         rs->sr_flags ^= REP_ENTRY_MUSTRELEASE;
2545                                                 } else if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
2546                                                         entry_free( rs->sr_entry );
2547                                                 }
2548                                                 rs->sr_entry = e;
2549                                                 rs->sr_flags |=
2550                                                         REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED;
2551                                                 a = attr_find( rs->sr_entry->e_attrs,
2552                                                         slap_schema.si_ad_contextCSN );
2553                                         }
2554                                         if ( a->a_nvals != a->a_vals ) {
2555                                                 ber_bvarray_free( a->a_nvals );
2556                                         }
2557                                         a->a_nvals = NULL;
2558                                         ber_bvarray_free( a->a_vals );
2559                                         a->a_vals = NULL;
2560                                         a->a_numvals = 0;
2561                                 }
2562                                 attr_valadd( a, si->si_ctxcsn, si->si_ctxcsn, si->si_numcsns );
2563                         }
2564                         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2565                 }
2566         }
2567         return SLAP_CB_CONTINUE;
2568 }
2569
2570 enum {
2571         SP_CHKPT = 1,
2572         SP_SESSL,
2573         SP_NOPRES,
2574         SP_USEHINT
2575 };
2576
2577 static ConfigDriver sp_cf_gen;
2578
2579 static ConfigTable spcfg[] = {
2580         { "syncprov-checkpoint", "ops> <minutes", 3, 3, 0, ARG_MAGIC|SP_CHKPT,
2581                 sp_cf_gen, "( OLcfgOvAt:1.1 NAME 'olcSpCheckpoint' "
2582                         "DESC 'ContextCSN checkpoint interval in ops and minutes' "
2583                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2584         { "syncprov-sessionlog", "ops", 2, 2, 0, ARG_INT|ARG_MAGIC|SP_SESSL,
2585                 sp_cf_gen, "( OLcfgOvAt:1.2 NAME 'olcSpSessionlog' "
2586                         "DESC 'Session log size in ops' "
2587                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
2588         { "syncprov-nopresent", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_NOPRES,
2589                 sp_cf_gen, "( OLcfgOvAt:1.3 NAME 'olcSpNoPresent' "
2590                         "DESC 'Omit Present phase processing' "
2591                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
2592         { "syncprov-reloadhint", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_USEHINT,
2593                 sp_cf_gen, "( OLcfgOvAt:1.4 NAME 'olcSpReloadHint' "
2594                         "DESC 'Observe Reload Hint in Request control' "
2595                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
2596         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2597 };
2598
2599 static ConfigOCs spocs[] = {
2600         { "( OLcfgOvOc:1.1 "
2601                 "NAME 'olcSyncProvConfig' "
2602                 "DESC 'SyncRepl Provider configuration' "
2603                 "SUP olcOverlayConfig "
2604                 "MAY ( olcSpCheckpoint "
2605                         "$ olcSpSessionlog "
2606                         "$ olcSpNoPresent "
2607                         "$ olcSpReloadHint "
2608                 ") )",
2609                         Cft_Overlay, spcfg },
2610         { NULL, 0, NULL }
2611 };
2612
2613 static int
2614 sp_cf_gen(ConfigArgs *c)
2615 {
2616         slap_overinst           *on = (slap_overinst *)c->bi;
2617         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2618         int rc = 0;
2619
2620         if ( c->op == SLAP_CONFIG_EMIT ) {
2621                 switch ( c->type ) {
2622                 case SP_CHKPT:
2623                         if ( si->si_chkops || si->si_chktime ) {
2624                                 struct berval bv;
2625                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2626                                         "%d %d", si->si_chkops, si->si_chktime );
2627                                 if ( bv.bv_len >= sizeof( c->cr_msg ) ) {
2628                                         rc = 1;
2629                                 } else {
2630                                         bv.bv_val = c->cr_msg;
2631                                         value_add_one( &c->rvalue_vals, &bv );
2632                                 }
2633                         } else {
2634                                 rc = 1;
2635                         }
2636                         break;
2637                 case SP_SESSL:
2638                         if ( si->si_logs ) {
2639                                 c->value_int = si->si_logs->sl_size;
2640                         } else {
2641                                 rc = 1;
2642                         }
2643                         break;
2644                 case SP_NOPRES:
2645                         if ( si->si_nopres ) {
2646                                 c->value_int = 1;
2647                         } else {
2648                                 rc = 1;
2649                         }
2650                         break;
2651                 case SP_USEHINT:
2652                         if ( si->si_usehint ) {
2653                                 c->value_int = 1;
2654                         } else {
2655                                 rc = 1;
2656                         }
2657                         break;
2658                 }
2659                 return rc;
2660         } else if ( c->op == LDAP_MOD_DELETE ) {
2661                 switch ( c->type ) {
2662                 case SP_CHKPT:
2663                         si->si_chkops = 0;
2664                         si->si_chktime = 0;
2665                         break;
2666                 case SP_SESSL:
2667                         if ( si->si_logs )
2668                                 si->si_logs->sl_size = 0;
2669                         else
2670                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2671                         break;
2672                 case SP_NOPRES:
2673                         if ( si->si_nopres )
2674                                 si->si_nopres = 0;
2675                         else
2676                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2677                         break;
2678                 case SP_USEHINT:
2679                         if ( si->si_usehint )
2680                                 si->si_usehint = 0;
2681                         else
2682                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2683                         break;
2684                 }
2685                 return rc;
2686         }
2687         switch ( c->type ) {
2688         case SP_CHKPT:
2689                 if ( lutil_atoi( &si->si_chkops, c->argv[1] ) != 0 ) {
2690                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint ops # \"%s\"",
2691                                 c->argv[0], c->argv[1] );
2692                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2693                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2694                         return ARG_BAD_CONF;
2695                 }
2696                 if ( si->si_chkops <= 0 ) {
2697                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint ops # \"%d\"",
2698                                 c->argv[0], si->si_chkops );
2699                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2700                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2701                         return ARG_BAD_CONF;
2702                 }
2703                 if ( lutil_atoi( &si->si_chktime, c->argv[2] ) != 0 ) {
2704                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint time \"%s\"",
2705                                 c->argv[0], c->argv[1] );
2706                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2707                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2708                         return ARG_BAD_CONF;
2709                 }
2710                 if ( si->si_chktime <= 0 ) {
2711                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint time \"%d\"",
2712                                 c->argv[0], si->si_chkops );
2713                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2714                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2715                         return ARG_BAD_CONF;
2716                 }
2717                 si->si_chktime *= 60;
2718                 break;
2719         case SP_SESSL: {
2720                 sessionlog *sl;
2721                 int size = c->value_int;
2722
2723                 if ( size < 0 ) {
2724                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s size %d is negative",
2725                                 c->argv[0], size );
2726                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2727                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2728                         return ARG_BAD_CONF;
2729                 }
2730                 sl = si->si_logs;
2731                 if ( !sl ) {
2732                         sl = ch_malloc( sizeof( sessionlog ) + LDAP_LUTIL_CSNSTR_BUFSIZE );
2733                         sl->sl_mincsn.bv_val = (char *)(sl+1);
2734                         sl->sl_mincsn.bv_len = 0;
2735                         sl->sl_num = 0;
2736                         sl->sl_head = sl->sl_tail = NULL;
2737                         ldap_pvt_thread_mutex_init( &sl->sl_mutex );
2738                         si->si_logs = sl;
2739                 }
2740                 sl->sl_size = size;
2741                 }
2742                 break;
2743         case SP_NOPRES:
2744                 si->si_nopres = c->value_int;
2745                 break;
2746         case SP_USEHINT:
2747                 si->si_usehint = c->value_int;
2748                 break;
2749         }
2750         return rc;
2751 }
2752
2753 /* ITS#3456 we cannot run this search on the main thread, must use a
2754  * child thread in order to insure we have a big enough stack.
2755  */
2756 static void *
2757 syncprov_db_otask(
2758         void *ptr
2759 )
2760 {
2761         syncprov_findcsn( ptr, FIND_MAXCSN );
2762         return NULL;
2763 }
2764
2765 /* Read any existing contextCSN from the underlying db.
2766  * Then search for any entries newer than that. If no value exists,
2767  * just generate it. Cache whatever result.
2768  */
2769 static int
2770 syncprov_db_open(
2771         BackendDB *be,
2772         ConfigReply *cr
2773 )
2774 {
2775         slap_overinst   *on = (slap_overinst *) be->bd_info;
2776         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2777
2778         Connection conn = { 0 };
2779         OperationBuffer opbuf;
2780         Operation *op;
2781         Entry *e = NULL;
2782         Attribute *a;
2783         int rc;
2784         void *thrctx = NULL;
2785
2786         if ( !SLAP_LASTMOD( be )) {
2787                 Debug( LDAP_DEBUG_ANY,
2788                         "syncprov_db_open: invalid config, lastmod must be enabled\n", 0, 0, 0 );
2789                 return -1;
2790         }
2791
2792         if ( slapMode & SLAP_TOOL_MODE ) {
2793                 return 0;
2794         }
2795
2796         rc = overlay_register_control( be, LDAP_CONTROL_SYNC );
2797         if ( rc ) {
2798                 return rc;
2799         }
2800
2801         thrctx = ldap_pvt_thread_pool_context();
2802         connection_fake_init( &conn, &opbuf, thrctx );
2803         op = &opbuf.ob_op;
2804         op->o_bd = be;
2805         op->o_dn = be->be_rootdn;
2806         op->o_ndn = be->be_rootndn;
2807
2808         rc = overlay_entry_get_ov( op, be->be_nsuffix, NULL,
2809                 slap_schema.si_ad_contextCSN, 0, &e, on );
2810
2811         if ( e ) {
2812                 ldap_pvt_thread_t tid;
2813
2814                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
2815                 if ( a ) {
2816                         ber_bvarray_dup_x( &si->si_ctxcsn, a->a_vals, NULL );
2817                         si->si_numcsns = a->a_numvals;
2818                         si->si_sids = slap_parse_csn_sids( si->si_ctxcsn, a->a_numvals, NULL );
2819                 }
2820                 overlay_entry_release_ov( op, e, 0, on );
2821                 if ( si->si_ctxcsn && !SLAP_DBCLEAN( be )) {
2822                         op->o_req_dn = be->be_suffix[0];
2823                         op->o_req_ndn = be->be_nsuffix[0];
2824                         op->ors_scope = LDAP_SCOPE_SUBTREE;
2825                         ldap_pvt_thread_create( &tid, 0, syncprov_db_otask, op );
2826                         ldap_pvt_thread_join( tid, NULL );
2827                 }
2828         }
2829
2830         /* Didn't find a contextCSN, should we generate one? */
2831         if ( !si->si_ctxcsn ) {
2832                 char csnbuf[ LDAP_LUTIL_CSNSTR_BUFSIZE ];
2833                 struct berval csn;
2834
2835                 if ( SLAP_SYNC_SHADOW( op->o_bd )) {
2836                 /* If we're also a consumer, then don't generate anything.
2837                  * Wait for our provider to send it to us, or for a local
2838                  * modify if we have multimaster.
2839                  */
2840                         goto out;
2841                 }
2842                 csn.bv_val = csnbuf;
2843                 csn.bv_len = sizeof( csnbuf );
2844                 slap_get_csn( op, &csn, 0 );
2845                 value_add_one( &si->si_ctxcsn, &csn );
2846                 si->si_numcsns = 1;
2847                 si->si_sids = ch_malloc( sizeof(int) );
2848                 si->si_sids[0] = slap_serverID;
2849
2850                 /* make sure we do a checkpoint on close */
2851                 si->si_numops++;
2852         }
2853
2854 out:
2855         op->o_bd->bd_info = (BackendInfo *)on;
2856         return 0;
2857 }
2858
2859 /* Write the current contextCSN into the underlying db.
2860  */
2861 static int
2862 syncprov_db_close(
2863         BackendDB *be,
2864         ConfigReply *cr
2865 )
2866 {
2867     slap_overinst   *on = (slap_overinst *) be->bd_info;
2868     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2869
2870         if ( slapMode & SLAP_TOOL_MODE ) {
2871                 return 0;
2872         }
2873         if ( si->si_numops ) {
2874                 Connection conn = {0};
2875                 OperationBuffer opbuf;
2876                 Operation *op;
2877                 SlapReply rs = {REP_RESULT};
2878                 void *thrctx;
2879
2880                 thrctx = ldap_pvt_thread_pool_context();
2881                 connection_fake_init( &conn, &opbuf, thrctx );
2882                 op = &opbuf.ob_op;
2883                 op->o_bd = be;
2884                 op->o_dn = be->be_rootdn;
2885                 op->o_ndn = be->be_rootndn;
2886                 syncprov_checkpoint( op, &rs, on );
2887         }
2888
2889     return 0;
2890 }
2891
2892 static int
2893 syncprov_db_init(
2894         BackendDB *be,
2895         ConfigReply *cr
2896 )
2897 {
2898         slap_overinst   *on = (slap_overinst *)be->bd_info;
2899         syncprov_info_t *si;
2900
2901         if ( SLAP_ISGLOBALOVERLAY( be ) ) {
2902                 Debug( LDAP_DEBUG_ANY,
2903                         "syncprov must be instantiated within a database.\n",
2904                         0, 0, 0 );
2905                 return 1;
2906         }
2907
2908         si = ch_calloc(1, sizeof(syncprov_info_t));
2909         on->on_bi.bi_private = si;
2910         ldap_pvt_thread_rdwr_init( &si->si_csn_rwlock );
2911         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
2912         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
2913
2914         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
2915         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
2916         csn_anlist[1].an_desc = slap_schema.si_ad_entryUUID;
2917         csn_anlist[1].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2918
2919         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
2920         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2921
2922         return 0;
2923 }
2924
2925 static int
2926 syncprov_db_destroy(
2927         BackendDB *be,
2928         ConfigReply *cr
2929 )
2930 {
2931         slap_overinst   *on = (slap_overinst *)be->bd_info;
2932         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2933
2934         if ( si ) {
2935                 if ( si->si_logs ) {
2936                         slog_entry *se = si->si_logs->sl_head;
2937
2938                         while ( se ) {
2939                                 slog_entry *se_next = se->se_next;
2940                                 ch_free( se );
2941                                 se = se_next;
2942                         }
2943                                 
2944                         ch_free( si->si_logs );
2945                 }
2946                 if ( si->si_ctxcsn )
2947                         ber_bvarray_free( si->si_ctxcsn );
2948                 if ( si->si_sids )
2949                         ch_free( si->si_sids );
2950                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
2951                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
2952                 ldap_pvt_thread_rdwr_destroy( &si->si_csn_rwlock );
2953                 ch_free( si );
2954         }
2955
2956         return 0;
2957 }
2958
2959 static int syncprov_parseCtrl (
2960         Operation *op,
2961         SlapReply *rs,
2962         LDAPControl *ctrl )
2963 {
2964         ber_tag_t tag;
2965         BerElementBuffer berbuf;
2966         BerElement *ber = (BerElement *)&berbuf;
2967         ber_int_t mode;
2968         ber_len_t len;
2969         struct berval cookie = BER_BVNULL;
2970         sync_control *sr;
2971         int rhint = 0;
2972
2973         if ( op->o_sync != SLAP_CONTROL_NONE ) {
2974                 rs->sr_text = "Sync control specified multiple times";
2975                 return LDAP_PROTOCOL_ERROR;
2976         }
2977
2978         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
2979                 rs->sr_text = "Sync control specified with pagedResults control";
2980                 return LDAP_PROTOCOL_ERROR;
2981         }
2982
2983         if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
2984                 rs->sr_text = "Sync control value is absent";
2985                 return LDAP_PROTOCOL_ERROR;
2986         }
2987
2988         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
2989                 rs->sr_text = "Sync control value is empty";
2990                 return LDAP_PROTOCOL_ERROR;
2991         }
2992
2993         /* Parse the control value
2994          *      syncRequestValue ::= SEQUENCE {
2995          *              mode   ENUMERATED {
2996          *                      -- 0 unused
2997          *                      refreshOnly             (1),
2998          *                      -- 2 reserved
2999          *                      refreshAndPersist       (3)
3000          *              },
3001          *              cookie  syncCookie OPTIONAL
3002          *      }
3003          */
3004
3005         ber_init2( ber, &ctrl->ldctl_value, 0 );
3006
3007         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
3008                 rs->sr_text = "Sync control : mode decoding error";
3009                 return LDAP_PROTOCOL_ERROR;
3010         }
3011
3012         switch( mode ) {
3013         case LDAP_SYNC_REFRESH_ONLY:
3014                 mode = SLAP_SYNC_REFRESH;
3015                 break;
3016         case LDAP_SYNC_REFRESH_AND_PERSIST:
3017                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
3018                 break;
3019         default:
3020                 rs->sr_text = "Sync control : unknown update mode";
3021                 return LDAP_PROTOCOL_ERROR;
3022         }
3023
3024         tag = ber_peek_tag( ber, &len );
3025
3026         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
3027                 if (( ber_scanf( ber, /*{*/ "m", &cookie )) == LBER_ERROR ) {
3028                         rs->sr_text = "Sync control : cookie decoding error";
3029                         return LDAP_PROTOCOL_ERROR;
3030                 }
3031                 tag = ber_peek_tag( ber, &len );
3032         }
3033         if ( tag == LDAP_TAG_RELOAD_HINT ) {
3034                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
3035                         rs->sr_text = "Sync control : rhint decoding error";
3036                         return LDAP_PROTOCOL_ERROR;
3037                 }
3038         }
3039         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
3040                         rs->sr_text = "Sync control : decoding error";
3041                         return LDAP_PROTOCOL_ERROR;
3042         }
3043         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
3044         sr->sr_rhint = rhint;
3045         if (!BER_BVISNULL(&cookie)) {
3046                 ber_dupbv_x( &sr->sr_state.octet_str, &cookie, op->o_tmpmemctx );
3047                 /* If parse fails, pretend no cookie was sent */
3048                 if ( slap_parse_sync_cookie( &sr->sr_state, op->o_tmpmemctx ) ||
3049                         sr->sr_state.rid == -1 ) {
3050                         if ( sr->sr_state.ctxcsn ) {
3051                                 ber_bvarray_free_x( sr->sr_state.ctxcsn, op->o_tmpmemctx );
3052                                 sr->sr_state.ctxcsn = NULL;
3053                         }
3054                         sr->sr_state.numcsns = 0;
3055                 }
3056         }
3057
3058         op->o_controls[slap_cids.sc_LDAPsync] = sr;
3059
3060         op->o_sync = ctrl->ldctl_iscritical
3061                 ? SLAP_CONTROL_CRITICAL
3062                 : SLAP_CONTROL_NONCRITICAL;
3063
3064         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
3065
3066         return LDAP_SUCCESS;
3067 }
3068
3069 /* This overlay is set up for dynamic loading via moduleload. For static
3070  * configuration, you'll need to arrange for the slap_overinst to be
3071  * initialized and registered by some other function inside slapd.
3072  */
3073
3074 static slap_overinst            syncprov;
3075
3076 int
3077 syncprov_initialize()
3078 {
3079         int rc;
3080
3081         rc = register_supported_control( LDAP_CONTROL_SYNC,
3082                 SLAP_CTRL_SEARCH, NULL,
3083                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
3084         if ( rc != LDAP_SUCCESS ) {
3085                 Debug( LDAP_DEBUG_ANY,
3086                         "syncprov_init: Failed to register control %d\n", rc, 0, 0 );
3087                 return rc;
3088         }
3089
3090         syncprov.on_bi.bi_type = "syncprov";
3091         syncprov.on_bi.bi_db_init = syncprov_db_init;
3092         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
3093         syncprov.on_bi.bi_db_open = syncprov_db_open;
3094         syncprov.on_bi.bi_db_close = syncprov_db_close;
3095
3096         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
3097         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
3098
3099         syncprov.on_bi.bi_op_add = syncprov_op_mod;
3100         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
3101         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
3102         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
3103         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
3104         syncprov.on_bi.bi_op_search = syncprov_op_search;
3105         syncprov.on_bi.bi_extended = syncprov_op_extended;
3106         syncprov.on_bi.bi_operational = syncprov_operational;
3107
3108         syncprov.on_bi.bi_cf_ocs = spocs;
3109
3110         generic_filter.f_desc = slap_schema.si_ad_objectClass;
3111
3112         rc = config_register_schema( spcfg, spocs );
3113         if ( rc ) return rc;
3114
3115         return overlay_register( &syncprov );
3116 }
3117
3118 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
3119 int
3120 init_module( int argc, char *argv[] )
3121 {
3122         return syncprov_initialize();
3123 }
3124 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
3125
3126 #endif /* defined(SLAPD_OVER_SYNCPROV) */