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