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