]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
Fix prev commit op initialization, runqueue startup latency
[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-2005 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 /* A modify request on a particular entry */
32 typedef struct modinst {
33         struct modinst *mi_next;
34         Operation *mi_op;
35 } modinst;
36
37 typedef struct modtarget {
38         struct modinst *mt_mods;
39         struct modinst *mt_tail;
40         Operation *mt_op;
41         ldap_pvt_thread_mutex_t mt_mutex;
42 } modtarget;
43
44 /* A queued result of a persistent search */
45 typedef struct syncres {
46         struct syncres *s_next;
47         struct berval s_dn;
48         struct berval s_ndn;
49         struct berval s_uuid;
50         struct berval s_csn;
51         char s_mode;
52         char s_isreference;
53 } syncres;
54
55 /* Record of a persistent search */
56 typedef struct syncops {
57         struct syncops *s_next;
58         struct berval   s_base;         /* ndn of search base */
59         ID              s_eid;          /* entryID of search base */
60         Operation       *s_op;          /* search op */
61         int             s_rid;
62         struct berval s_filterstr;
63         int             s_flags;        /* search status */
64 #define PS_IS_REFRESHING        0x01
65 #define PS_IS_DETACHED          0x02
66 #define PS_WROTE_BASE           0x04
67 #define PS_FIND_BASE            0x08
68
69         int             s_inuse;        /* reference count */
70         struct syncres *s_res;
71         struct syncres *s_restail;
72         struct re_s     *s_qtask;       /* task for playing psearch responses */
73 #define RUNQ_INTERVAL   36000   /* a long time */
74         ldap_pvt_thread_mutex_t s_mutex;
75 } syncops;
76
77 /* A received sync control */
78 typedef struct sync_control {
79         struct sync_cookie sr_state;
80         int sr_rhint;
81 } sync_control;
82
83 #if 0 /* moved back to slap.h */
84 #define o_sync  o_ctrlflag[slap_cids.sc_LDAPsync]
85 #endif
86 /* o_sync_mode uses data bits of o_sync */
87 #define o_sync_mode     o_ctrlflag[slap_cids.sc_LDAPsync]
88
89 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
90 #define SLAP_SYNC_REFRESH                               (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
91 #define SLAP_SYNC_PERSIST                               (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
92 #define SLAP_SYNC_REFRESH_AND_PERSIST   (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
93
94 /* Record of which searches matched at premodify step */
95 typedef struct syncmatches {
96         struct syncmatches *sm_next;
97         syncops *sm_op;
98 } syncmatches;
99
100 /* Session log data */
101 typedef struct slog_entry {
102         struct slog_entry *se_next;
103         struct berval se_uuid;
104         struct berval se_csn;
105         ber_tag_t       se_tag;
106 } slog_entry;
107
108 typedef struct sessionlog {
109         struct berval   sl_mincsn;
110         int             sl_num;
111         int             sl_size;
112         slog_entry *sl_head;
113         slog_entry *sl_tail;
114         ldap_pvt_thread_mutex_t sl_mutex;
115 } sessionlog;
116
117 /* The main state for this overlay */
118 typedef struct syncprov_info_t {
119         syncops         *si_ops;
120         struct berval   si_ctxcsn;      /* ldapsync context */
121         int             si_chkops;      /* checkpointing info */
122         int             si_chktime;
123         int             si_numops;      /* number of ops since last checkpoint */
124         int             si_nopres;      /* Skip present phase */
125         time_t  si_chklast;     /* time of last checkpoint */
126         Avlnode *si_mods;       /* entries being modified */
127         sessionlog      *si_logs;
128         ldap_pvt_thread_mutex_t si_csn_mutex;
129         ldap_pvt_thread_mutex_t si_ops_mutex;
130         ldap_pvt_thread_mutex_t si_mods_mutex;
131         char            si_ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
132 } syncprov_info_t;
133
134 typedef struct opcookie {
135         slap_overinst *son;
136         syncmatches *smatches;
137         struct berval sdn;      /* DN of entry, for deletes */
138         struct berval sndn;
139         struct berval suuid;    /* UUID of entry */
140         struct berval sctxcsn;
141         int sreference; /* Is the entry a reference? */
142 } opcookie;
143
144 typedef struct fbase_cookie {
145         struct berval *fdn;     /* DN of a modified entry, for scope testing */
146         syncops *fss;   /* persistent search we're testing against */
147         int fbase;      /* if TRUE we found the search base and it's still valid */
148         int fscope;     /* if TRUE then fdn is within the psearch scope */
149 } fbase_cookie;
150
151 static AttributeName csn_anlist[3];
152 static AttributeName uuid_anlist[2];
153
154 /* Build a LDAPsync intermediate state control */
155 static int
156 syncprov_state_ctrl(
157         Operation       *op,
158         SlapReply       *rs,
159         Entry           *e,
160         int             entry_sync_state,
161         LDAPControl     **ctrls,
162         int             num_ctrls,
163         int             send_cookie,
164         struct berval   *cookie )
165 {
166         Attribute* a;
167         int ret;
168
169         BerElementBuffer berbuf;
170         BerElement *ber = (BerElement *)&berbuf;
171
172         struct berval   entryuuid_bv = BER_BVNULL;
173
174         ber_init2( ber, 0, LBER_USE_DER );
175         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
176
177         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
178
179         for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
180                 AttributeDescription *desc = a->a_desc;
181                 if ( desc == slap_schema.si_ad_entryUUID ) {
182                         entryuuid_bv = a->a_nvals[0];
183                         break;
184                 }
185         }
186
187         /* FIXME: what if entryuuid is NULL or empty ? */
188
189         if ( send_cookie && cookie ) {
190                 ber_printf( ber, "{eOON}",
191                         entry_sync_state, &entryuuid_bv, cookie );
192         } else {
193                 ber_printf( ber, "{eON}",
194                         entry_sync_state, &entryuuid_bv );
195         }
196
197         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
198         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
199         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
200
201         ber_free_buf( ber );
202
203         if ( ret < 0 ) {
204                 Debug( LDAP_DEBUG_TRACE,
205                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
206                         0, 0, 0 );
207                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
208                 return ret;
209         }
210
211         return LDAP_SUCCESS;
212 }
213
214 /* Build a LDAPsync final state control */
215 static int
216 syncprov_done_ctrl(
217         Operation       *op,
218         SlapReply       *rs,
219         LDAPControl     **ctrls,
220         int                     num_ctrls,
221         int                     send_cookie,
222         struct berval *cookie,
223         int                     refreshDeletes )
224 {
225         int ret;
226         BerElementBuffer berbuf;
227         BerElement *ber = (BerElement *)&berbuf;
228
229         ber_init2( ber, NULL, LBER_USE_DER );
230         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
231
232         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
233
234         ber_printf( ber, "{" );
235         if ( send_cookie && cookie ) {
236                 ber_printf( ber, "O", cookie );
237         }
238         if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
239                 ber_printf( ber, "b", refreshDeletes );
240         }
241         ber_printf( ber, "N}" );
242
243         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
244         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
245         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
246
247         ber_free_buf( ber );
248
249         if ( ret < 0 ) {
250                 Debug( LDAP_DEBUG_TRACE,
251                         "syncprov_done_ctrl: ber_flatten2 failed\n",
252                         0, 0, 0 );
253                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
254                 return ret;
255         }
256
257         return LDAP_SUCCESS;
258 }
259
260 static int
261 syncprov_sendinfo(
262         Operation       *op,
263         SlapReply       *rs,
264         int                     type,
265         struct berval *cookie,
266         int                     refreshDone,
267         BerVarray       syncUUIDs,
268         int                     refreshDeletes )
269 {
270         BerElementBuffer berbuf;
271         BerElement *ber = (BerElement *)&berbuf;
272         struct berval rspdata;
273
274         int ret;
275
276         ber_init2( ber, NULL, LBER_USE_DER );
277         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
278
279         if ( type ) {
280                 switch ( type ) {
281                 case LDAP_TAG_SYNC_NEW_COOKIE:
282                         ber_printf( ber, "tO", type, cookie );
283                         break;
284                 case LDAP_TAG_SYNC_REFRESH_DELETE:
285                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
286                         ber_printf( ber, "t{", type );
287                         if ( cookie ) {
288                                 ber_printf( ber, "O", cookie );
289                         }
290                         if ( refreshDone == 0 ) {
291                                 ber_printf( ber, "b", refreshDone );
292                         }
293                         ber_printf( ber, "N}" );
294                         break;
295                 case LDAP_TAG_SYNC_ID_SET:
296                         ber_printf( ber, "t{", type );
297                         if ( cookie ) {
298                                 ber_printf( ber, "O", cookie );
299                         }
300                         if ( refreshDeletes == 1 ) {
301                                 ber_printf( ber, "b", refreshDeletes );
302                         }
303                         ber_printf( ber, "[W]", syncUUIDs );
304                         ber_printf( ber, "N}" );
305                         break;
306                 default:
307                         Debug( LDAP_DEBUG_TRACE,
308                                 "syncprov_sendinfo: invalid syncinfo type (%d)\n",
309                                 type, 0, 0 );
310                         return LDAP_OTHER;
311                 }
312         }
313
314         ret = ber_flatten2( ber, &rspdata, 0 );
315
316         if ( ret < 0 ) {
317                 Debug( LDAP_DEBUG_TRACE,
318                         "syncprov_sendinfo: ber_flatten2 failed\n",
319                         0, 0, 0 );
320                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
321                 return ret;
322         }
323
324         rs->sr_rspoid = LDAP_SYNC_INFO;
325         rs->sr_rspdata = &rspdata;
326         send_ldap_intermediate( op, rs );
327         rs->sr_rspdata = NULL;
328         ber_free_buf( ber );
329
330         return LDAP_SUCCESS;
331 }
332
333 /* Find a modtarget in an AVL tree */
334 static int
335 sp_avl_cmp( const void *c1, const void *c2 )
336 {
337         const modtarget *m1, *m2;
338         int rc;
339
340         m1 = c1; m2 = c2;
341         rc = m1->mt_op->o_req_ndn.bv_len - m2->mt_op->o_req_ndn.bv_len;
342
343         if ( rc ) return rc;
344         return ber_bvcmp( &m1->mt_op->o_req_ndn, &m2->mt_op->o_req_ndn );
345 }
346
347 /* syncprov_findbase:
348  *   finds the true DN of the base of a search (with alias dereferencing) and
349  * checks to make sure the base entry doesn't get replaced with a different
350  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
351  * change is detected, any persistent search on this base must be terminated /
352  * reloaded.
353  *   On the first call, we just save the DN and entryID. On subsequent calls
354  * we compare the DN and entryID with the saved values.
355  */
356 static int
357 findbase_cb( Operation *op, SlapReply *rs )
358 {
359         slap_callback *sc = op->o_callback;
360
361         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
362                 fbase_cookie *fc = sc->sc_private;
363
364                 /* If no entryID, we're looking for the first time.
365                  * Just store whatever we got.
366                  */
367                 if ( fc->fss->s_eid == NOID ) {
368                         fc->fbase = 2;
369                         fc->fss->s_eid = rs->sr_entry->e_id;
370                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
371
372                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
373                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
374
375                 /* OK, the DN is the same and the entryID is the same. */
376                         fc->fbase = 1;
377                 }
378         }
379         if ( rs->sr_err != LDAP_SUCCESS ) {
380                 Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err,0,0 );
381         }
382         return LDAP_SUCCESS;
383 }
384
385 static int
386 syncprov_findbase( Operation *op, fbase_cookie *fc )
387 {
388         opcookie *opc = op->o_callback->sc_private;
389         slap_overinst *on = opc->son;
390
391         /* Use basic parameters from syncrepl search, but use
392          * current op's threadctx / tmpmemctx
393          */
394         ldap_pvt_thread_mutex_lock( &fc->fss->s_mutex );
395         if ( fc->fss->s_flags & PS_FIND_BASE ) {
396                 slap_callback cb = {0};
397                 Operation fop;
398                 SlapReply frs = { REP_RESULT };
399                 int rc;
400
401                 fc->fss->s_flags ^= PS_FIND_BASE;
402                 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
403
404                 fop = *fc->fss->s_op;
405
406                 fop.o_hdr = op->o_hdr;
407                 fop.o_bd = op->o_bd;
408                 fop.o_time = op->o_time;
409                 fop.o_tincr = op->o_tincr;
410
411                 cb.sc_response = findbase_cb;
412                 cb.sc_private = fc;
413
414                 fop.o_sync_mode = 0;    /* turn off sync mode */
415                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
416                 fop.o_callback = &cb;
417                 fop.o_tag = LDAP_REQ_SEARCH;
418                 fop.ors_scope = LDAP_SCOPE_BASE;
419                 fop.ors_limit = NULL;
420                 fop.ors_slimit = 1;
421                 fop.ors_tlimit = SLAP_NO_LIMIT;
422                 fop.ors_attrs = slap_anlist_no_attrs;
423                 fop.ors_attrsonly = 1;
424
425                 fop.o_bd->bd_info = on->on_info->oi_orig;
426                 rc = fop.o_bd->be_search( &fop, &frs );
427                 fop.o_bd->bd_info = (BackendInfo *)on;
428         } else {
429                 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
430                 fc->fbase = 1;
431         }
432
433         /* After the first call, see if the fdn resides in the scope */
434         if ( fc->fbase == 1 ) {
435                 switch ( fc->fss->s_op->ors_scope ) {
436                 case LDAP_SCOPE_BASE:
437                         fc->fscope = dn_match( fc->fdn, &fc->fss->s_base );
438                         break;
439                 case LDAP_SCOPE_ONELEVEL: {
440                         struct berval pdn;
441                         dnParent( fc->fdn, &pdn );
442                         fc->fscope = dn_match( &pdn, &fc->fss->s_base );
443                         break; }
444                 case LDAP_SCOPE_SUBTREE:
445                         fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base );
446                         break;
447 #ifdef LDAP_SCOPE_SUBORDINATE
448                 case LDAP_SCOPE_SUBORDINATE:
449                         fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base ) &&
450                                 !dn_match( fc->fdn, &fc->fss->s_base );
451                         break;
452 #endif
453                 }
454         }
455
456         if ( fc->fbase )
457                 return LDAP_SUCCESS;
458
459         /* If entryID has changed, then the base of this search has
460          * changed. Invalidate the psearch.
461          */
462         return LDAP_NO_SUCH_OBJECT;
463 }
464
465 /* syncprov_findcsn:
466  *   This function has three different purposes, but they all use a search
467  * that filters on entryCSN so they're combined here.
468  * 1: at startup time, after a contextCSN has been read from the database,
469  * we search for all entries with CSN >= contextCSN in case the contextCSN
470  * was not checkpointed at the previous shutdown.
471  *
472  * 2: when the current contextCSN is known and we have a sync cookie, we search
473  * for one entry with CSN = the cookie CSN. If not found, try <= cookie CSN.
474  * If an entry is found, the cookie CSN is valid, otherwise it is stale.
475  *
476  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
477  * CSN, and generate Present records for them. We always collect this result
478  * in SyncID sets, even if there's only one match.
479  */
480 #define FIND_MAXCSN     1
481 #define FIND_CSN        2
482 #define FIND_PRESENT    3
483
484 static int
485 findmax_cb( Operation *op, SlapReply *rs )
486 {
487         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
488                 struct berval *maxcsn = op->o_callback->sc_private;
489                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
490                         slap_schema.si_ad_entryCSN );
491
492                 if ( a && ber_bvcmp( &a->a_vals[0], maxcsn ) > 0 ) {
493                         maxcsn->bv_len = a->a_vals[0].bv_len;
494                         strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
495                 }
496         }
497         return LDAP_SUCCESS;
498 }
499
500 static int
501 findcsn_cb( Operation *op, SlapReply *rs )
502 {
503         slap_callback *sc = op->o_callback;
504
505         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
506                 sc->sc_private = (void *)1;
507         }
508         return LDAP_SUCCESS;
509 }
510
511 /* Build a list of entryUUIDs for sending in a SyncID set */
512
513 #define UUID_LEN        16
514
515 typedef struct fpres_cookie {
516         int num;
517         BerVarray uuids;
518         char *last;
519 } fpres_cookie;
520
521 static int
522 findpres_cb( Operation *op, SlapReply *rs )
523 {
524         slap_callback *sc = op->o_callback;
525         fpres_cookie *pc = sc->sc_private;
526         Attribute *a;
527         int ret = SLAP_CB_CONTINUE;
528
529         switch ( rs->sr_type ) {
530         case REP_SEARCH:
531                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
532                 if ( a ) {
533                         pc->uuids[pc->num].bv_val = pc->last;
534                         AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
535                                 pc->uuids[pc->num].bv_len );
536                         pc->num++;
537                         pc->last = pc->uuids[pc->num].bv_val;
538                         pc->uuids[pc->num].bv_val = NULL;
539                 }
540                 ret = LDAP_SUCCESS;
541                 if ( pc->num != SLAP_SYNCUUID_SET_SIZE )
542                         break;
543                 /* FALLTHRU */
544         case REP_RESULT:
545                 ret = rs->sr_err;
546                 if ( pc->num ) {
547                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
548                                 0, pc->uuids, 0 );
549                         pc->uuids[pc->num].bv_val = pc->last;
550                         pc->num = 0;
551                         pc->last = pc->uuids[0].bv_val;
552                 }
553                 break;
554         default:
555                 break;
556         }
557         return ret;
558 }
559
560 static int
561 syncprov_findcsn( Operation *op, int mode )
562 {
563         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
564         syncprov_info_t         *si = on->on_bi.bi_private;
565
566         slap_callback cb = {0};
567         Operation fop;
568         SlapReply frs = { REP_RESULT };
569         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
570         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
571         struct berval maxcsn;
572         Filter cf, af;
573 #ifdef LDAP_COMP_MATCH
574         AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
575 #else
576         AttributeAssertion eq = { NULL, BER_BVNULL };
577 #endif
578         int i, rc = LDAP_SUCCESS;
579         fpres_cookie pcookie;
580         sync_control *srs = NULL;
581         int findcsn_retry = 1;
582
583         if ( mode != FIND_MAXCSN ) {
584                 srs = op->o_controls[slap_cids.sc_LDAPsync];
585
586                 if ( srs->sr_state.ctxcsn.bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
587                         return LDAP_OTHER;
588                 }
589         }
590
591         fop = *op;
592         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
593         /* We want pure entries, not referrals */
594         fop.o_managedsait = SLAP_CONTROL_CRITICAL;
595
596         cf.f_ava = &eq;
597         cf.f_av_desc = slap_schema.si_ad_entryCSN;
598         cf.f_next = NULL;
599
600         fop.o_callback = &cb;
601         fop.ors_limit = NULL;
602         fop.ors_tlimit = SLAP_NO_LIMIT;
603         fop.ors_filter = &cf;
604         fop.ors_filterstr.bv_val = buf;
605
606 again:
607         switch( mode ) {
608         case FIND_MAXCSN:
609                 cf.f_choice = LDAP_FILTER_GE;
610                 cf.f_av_value = si->si_ctxcsn;
611                 fop.ors_filterstr.bv_len = sprintf( buf, "(entryCSN>=%s)",
612                         cf.f_av_value.bv_val );
613                 fop.ors_attrsonly = 0;
614                 fop.ors_attrs = csn_anlist;
615                 fop.ors_slimit = SLAP_NO_LIMIT;
616                 cb.sc_private = &maxcsn;
617                 cb.sc_response = findmax_cb;
618                 strcpy( cbuf, si->si_ctxcsn.bv_val );
619                 maxcsn.bv_val = cbuf;
620                 maxcsn.bv_len = si->si_ctxcsn.bv_len;
621                 break;
622         case FIND_CSN:
623                 cf.f_av_value = srs->sr_state.ctxcsn;
624                 /* Look for exact match the first time */
625                 if ( findcsn_retry ) {
626                         cf.f_choice = LDAP_FILTER_EQUALITY;
627                         fop.ors_filterstr.bv_len = sprintf( buf, "(entryCSN=%s)",
628                                 cf.f_av_value.bv_val );
629                 /* On retry, look for <= */
630                 } else {
631                         cf.f_choice = LDAP_FILTER_LE;
632                         fop.ors_filterstr.bv_len = sprintf( buf, "(entryCSN<=%s)",
633                                 cf.f_av_value.bv_val );
634                 }
635                 fop.ors_attrsonly = 1;
636                 fop.ors_attrs = slap_anlist_no_attrs;
637                 fop.ors_slimit = 1;
638                 cb.sc_private = NULL;
639                 cb.sc_response = findcsn_cb;
640                 break;
641         case FIND_PRESENT:
642                 af.f_choice = LDAP_FILTER_AND;
643                 af.f_next = NULL;
644                 af.f_and = &cf;
645                 cf.f_choice = LDAP_FILTER_LE;
646                 cf.f_av_value = srs->sr_state.ctxcsn;
647                 cf.f_next = op->ors_filter;
648                 fop.ors_filter = &af;
649                 filter2bv_x( &fop, fop.ors_filter, &fop.ors_filterstr );
650                 fop.ors_attrsonly = 0;
651                 fop.ors_attrs = uuid_anlist;
652                 fop.ors_slimit = SLAP_NO_LIMIT;
653                 cb.sc_private = &pcookie;
654                 cb.sc_response = findpres_cb;
655                 pcookie.num = 0;
656
657                 /* preallocate storage for a full set */
658                 pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
659                         sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
660                         op->o_tmpmemctx );
661                 pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
662                 pcookie.uuids[0].bv_val = pcookie.last;
663                 pcookie.uuids[0].bv_len = UUID_LEN;
664                 for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
665                         pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
666                         pcookie.uuids[i].bv_len = UUID_LEN;
667                 }
668                 break;
669         }
670
671         fop.o_bd->bd_info = on->on_info->oi_orig;
672         fop.o_bd->be_search( &fop, &frs );
673         fop.o_bd->bd_info = (BackendInfo *)on;
674
675         switch( mode ) {
676         case FIND_MAXCSN:
677                 strcpy( si->si_ctxcsnbuf, maxcsn.bv_val );
678                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
679                 break;
680         case FIND_CSN:
681                 /* If matching CSN was not found, invalidate the context. */
682                 if ( !cb.sc_private ) {
683                         /* If we didn't find an exact match, then try for <= */
684                         if ( findcsn_retry ) {
685                                 findcsn_retry = 0;
686                                 goto again;
687                         }
688                         rc = LDAP_NO_SUCH_OBJECT;
689                 }
690                 break;
691         case FIND_PRESENT:
692                 op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
693                 op->o_tmpfree( fop.ors_filterstr.bv_val, op->o_tmpmemctx );
694                 break;
695         }
696
697         return rc;
698 }
699
700 /* Send a persistent search response */
701 static int
702 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, Entry **e, int mode)
703 {
704         slap_overinst *on = opc->son;
705
706         SlapReply rs = { REP_SEARCH };
707         LDAPControl *ctrls[2];
708         struct berval cookie;
709         Entry e_uuid = {0};
710         Attribute a_uuid = {0};
711
712         if ( so->s_op->o_abandon )
713                 return SLAPD_ABANDON;
714
715         ctrls[1] = NULL;
716         slap_compose_sync_cookie( op, &cookie, &opc->sctxcsn, so->s_rid );
717
718         e_uuid.e_attrs = &a_uuid;
719         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
720         a_uuid.a_nvals = &opc->suuid;
721         rs.sr_err = syncprov_state_ctrl( op, &rs, &e_uuid,
722                 mode, ctrls, 0, 1, &cookie );
723
724         rs.sr_ctrls = ctrls;
725         op->o_bd->bd_info = (BackendInfo *)on->on_info;
726         switch( mode ) {
727         case LDAP_SYNC_ADD:
728                 rs.sr_entry = *e;
729                 if ( rs.sr_entry->e_private )
730                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
731                 if ( opc->sreference ) {
732                         rs.sr_ref = get_entry_referrals( op, rs.sr_entry );
733                         send_search_reference( op, &rs );
734                         ber_bvarray_free( rs.sr_ref );
735                         if ( !rs.sr_entry )
736                                 *e = NULL;
737                         break;
738                 }
739                 /* fallthru */
740         case LDAP_SYNC_MODIFY:
741                 rs.sr_entry = *e;
742                 if ( rs.sr_entry->e_private )
743                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
744                 rs.sr_attrs = op->ors_attrs;
745                 send_search_entry( op, &rs );
746                 if ( !rs.sr_entry )
747                         *e = NULL;
748                 break;
749         case LDAP_SYNC_DELETE:
750                 e_uuid.e_attrs = NULL;
751                 e_uuid.e_name = opc->sdn;
752                 e_uuid.e_nname = opc->sndn;
753                 rs.sr_entry = &e_uuid;
754                 if ( opc->sreference ) {
755                         struct berval bv = BER_BVNULL;
756                         rs.sr_ref = &bv;
757                         send_search_reference( op, &rs );
758                 } else {
759                         send_search_entry( op, &rs );
760                 }
761                 break;
762         default:
763                 assert(0);
764         }
765         op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
766         rs.sr_ctrls = NULL;
767
768         return rs.sr_err;
769 }
770
771 /* Play back queued responses */
772 static int
773 syncprov_qplay( Operation *op, slap_overinst *on, syncops *so )
774 {
775         syncres *sr;
776         Entry *e;
777         opcookie opc;
778         int rc;
779
780         opc.son = on;
781         op->o_bd->bd_info = (BackendInfo *)on->on_info;
782
783         for (;;) {
784                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
785                 sr = so->s_res;
786                 if ( sr )
787                         so->s_res = sr->s_next;
788                 if ( !so->s_res )
789                         so->s_restail = NULL;
790                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
791
792                 if ( !sr )
793                         break;
794
795                 if ( !so->s_op->o_abandon ) {
796                         opc.sdn = sr->s_dn;
797                         opc.sndn = sr->s_ndn;
798                         opc.suuid = sr->s_uuid;
799                         opc.sctxcsn = sr->s_csn;
800                         opc.sreference = sr->s_isreference;
801                         e = NULL;
802
803                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
804                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
805                                 if ( rc ) {
806                                         ch_free( sr );
807                                         continue;
808                                 }
809                         }
810                         rc = syncprov_sendresp( op, &opc, so, &e, sr->s_mode );
811
812                         if ( e ) {
813                                 be_entry_release_rw( op, e, 0 );
814                         }
815                         if ( rc )
816                                 break;
817                 }
818
819                 ch_free( sr );
820         }
821         op->o_bd->bd_info = (BackendInfo *)on;
822         return rc;
823 }
824
825 /* runqueue task for playing back queued responses */
826 static void *
827 syncprov_qtask( void *ctx, void *arg )
828 {
829         struct re_s *rtask = arg;
830         syncops *so = rtask->arg;
831         slap_overinst *on = so->s_op->o_private;
832         char opbuf[OPERATION_BUFFER_SIZE];
833         Operation *op;
834         BackendDB be;
835
836         op = (Operation *)opbuf;
837         *op = *so->s_op;
838         op->o_hdr = (Opheader *)(op+1);
839         op->o_controls = (void **)(op->o_hdr+1);
840         memset( op->o_controls, 0, SLAP_MAX_CIDS * sizeof(void *));
841
842         *op->o_hdr = *so->s_op->o_hdr;
843
844         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx);
845         op->o_tmpmfuncs = &slap_sl_mfuncs;
846         op->o_threadctx = ctx;
847
848         /* syncprov_qplay expects a fake db */
849         be = *so->s_op->o_bd;
850         be.be_flags |= SLAP_DBFLAG_OVERLAY;
851         op->o_bd = &be;
852         op->o_private = NULL;
853         op->o_callback = NULL;
854
855         syncprov_qplay( op, on, so );
856
857         /* wait until we get explicitly scheduled again */
858         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
859         ldap_pvt_runqueue_stoptask( &slapd_rq, so->s_qtask );
860         ldap_pvt_runqueue_resched( &slapd_rq, so->s_qtask, 1 );
861         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
862
863         return NULL;
864 }
865
866 /* Queue a persistent search response */
867 static int
868 syncprov_qresp( opcookie *opc, syncops *so, int mode )
869 {
870         syncres *sr;
871
872         sr = ch_malloc(sizeof(syncres) + opc->suuid.bv_len + 1 +
873                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1 + opc->sctxcsn.bv_len + 1 );
874         sr->s_next = NULL;
875         sr->s_dn.bv_val = (char *)(sr + 1);
876         sr->s_dn.bv_len = opc->sdn.bv_len;
877         sr->s_mode = mode;
878         sr->s_isreference = opc->sreference;
879         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val, opc->sdn.bv_val );
880         sr->s_ndn.bv_len = opc->sndn.bv_len;
881         *(sr->s_ndn.bv_val++) = '\0';
882         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val, opc->sndn.bv_val );
883         sr->s_uuid.bv_len = opc->suuid.bv_len;
884         *(sr->s_uuid.bv_val++) = '\0';
885         sr->s_csn.bv_val = lutil_strcopy( sr->s_uuid.bv_val, opc->suuid.bv_val );
886         sr->s_csn.bv_len = opc->sctxcsn.bv_len;
887         strcpy( sr->s_csn.bv_val, opc->sctxcsn.bv_val );
888
889         ldap_pvt_thread_mutex_lock( &so->s_mutex );
890         if ( !so->s_res ) {
891                 so->s_res = sr;
892         } else {
893                 so->s_restail->s_next = sr;
894         }
895         so->s_restail = sr;
896
897         /* If the base of the psearch was modified, check it next time round */
898         if ( so->s_flags & PS_WROTE_BASE ) {
899                 so->s_flags ^= PS_WROTE_BASE;
900                 so->s_flags |= PS_FIND_BASE;
901         }
902         if ( so->s_flags & PS_IS_DETACHED ) {
903                 ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
904                 if ( !so->s_qtask ) {
905                         so->s_qtask = ldap_pvt_runqueue_insert( &slapd_rq, RUNQ_INTERVAL,
906                                 syncprov_qtask, so, "syncprov_qtask",
907                                 so->s_op->o_conn->c_peer_name.bv_val );
908                 } else {
909                         if (!ldap_pvt_runqueue_isrunning( &slapd_rq, so->s_qtask ) &&
910                                 !so->s_qtask->next_sched.tv_sec ) {
911                                 so->s_qtask->interval.tv_sec = 0;
912                                 ldap_pvt_runqueue_resched( &slapd_rq, so->s_qtask, 0 );
913                                 so->s_qtask->interval.tv_sec = RUNQ_INTERVAL;
914                         }
915                 }
916                 ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
917         }
918         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
919         return LDAP_SUCCESS;
920 }
921
922 static void
923 syncprov_free_syncop( syncops *so )
924 {
925         syncres *sr, *srnext;
926         GroupAssertion *ga, *gnext;
927
928         ldap_pvt_thread_mutex_lock( &so->s_mutex );
929         so->s_inuse--;
930         if ( so->s_inuse > 0 ) {
931                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
932                 return;
933         }
934         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
935         if ( so->s_flags & PS_IS_DETACHED ) {
936                 filter_free( so->s_op->ors_filter );
937                 for ( ga = so->s_op->o_groups; ga; ga=gnext ) {
938                         gnext = ga->ga_next;
939                         ch_free( ga );
940                 }
941                 ch_free( so->s_op );
942         }
943         ch_free( so->s_base.bv_val );
944         for ( sr=so->s_res; sr; sr=srnext ) {
945                 srnext = sr->s_next;
946                 ch_free( sr );
947         }
948         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
949         ch_free( so );
950 }
951
952 static int
953 syncprov_drop_psearch( syncops *so, int lock )
954 {
955         if ( so->s_flags & PS_IS_DETACHED ) {
956                 if ( lock )
957                         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
958                 so->s_op->o_conn->c_n_ops_executing--;
959                 so->s_op->o_conn->c_n_ops_completed++;
960                 LDAP_STAILQ_REMOVE( &so->s_op->o_conn->c_ops, so->s_op, slap_op,
961                         o_next );
962                 if ( lock )
963                         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
964         }
965         syncprov_free_syncop( so );
966
967         return 0;
968 }
969
970 static int
971 syncprov_ab_cleanup( Operation *op, SlapReply *rs )
972 {
973         slap_callback *sc = op->o_callback;
974         op->o_callback = sc->sc_next;
975         syncprov_drop_psearch( op->o_callback->sc_private, 0 );
976         op->o_tmpfree( sc, op->o_tmpmemctx );
977         return 0;
978 }
979
980 static int
981 syncprov_op_abandon( Operation *op, SlapReply *rs )
982 {
983         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
984         syncprov_info_t         *si = on->on_bi.bi_private;
985         syncops *so, *soprev;
986
987         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
988         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
989                 soprev=so, so=so->s_next ) {
990                 if ( so->s_op->o_connid == op->o_connid &&
991                         so->s_op->o_msgid == op->orn_msgid ) {
992                                 so->s_op->o_abandon = 1;
993                                 soprev->s_next = so->s_next;
994                                 break;
995                 }
996         }
997         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
998         if ( so ) {
999                 /* Is this really a Cancel exop? */
1000                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
1001                         so->s_op->o_cancel = SLAP_CANCEL_ACK;
1002                         rs->sr_err = LDAP_CANCELLED;
1003                         send_ldap_result( so->s_op, rs );
1004                         if ( so->s_flags & PS_IS_DETACHED ) {
1005                                 slap_callback *cb;
1006                                 cb = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1007                                 cb->sc_cleanup = syncprov_ab_cleanup;
1008                                 cb->sc_next = op->o_callback;
1009                                 cb->sc_private = so;
1010                                 return SLAP_CB_CONTINUE;
1011                         }
1012                 }
1013                 syncprov_drop_psearch( so, 0 );
1014         }
1015         return SLAP_CB_CONTINUE;
1016 }
1017
1018 /* Find which persistent searches are affected by this operation */
1019 static void
1020 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
1021 {
1022         slap_overinst *on = opc->son;
1023         syncprov_info_t         *si = on->on_bi.bi_private;
1024
1025         fbase_cookie fc;
1026         syncops *ss, *sprev, *snext;
1027         Entry *e;
1028         Attribute *a;
1029         int rc;
1030         struct berval newdn;
1031         int freefdn = 0;
1032
1033         fc.fdn = &op->o_req_ndn;
1034         /* compute new DN */
1035         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1036                 struct berval pdn;
1037                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
1038                 else dnParent( fc.fdn, &pdn );
1039                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
1040                 fc.fdn = &newdn;
1041                 freefdn = 1;
1042         }
1043         if ( op->o_tag != LDAP_REQ_ADD ) {
1044                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1045                 rc = be_entry_get_rw( op, fc.fdn, NULL, NULL, 0, &e );
1046                 /* If we're sending responses now, make a copy and unlock the DB */
1047                 if ( e && !saveit ) {
1048                         Entry *e2 = entry_dup( e );
1049                         be_entry_release_rw( op, e, 0 );
1050                         e = e2;
1051                 }
1052                 op->o_bd->bd_info = (BackendInfo *)on;
1053                 if ( rc ) return;
1054         } else {
1055                 e = op->ora_e;
1056         }
1057
1058         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
1059                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1060                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1061                 opc->sreference = is_entry_referral( e );
1062                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
1063                 if ( a )
1064                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
1065         } else if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1066                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1067                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1068                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1069                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1070         }
1071
1072         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1073         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
1074                 sprev = ss, ss=snext)
1075         {
1076                 syncmatches *sm;
1077                 int found = 0;
1078
1079                 snext = ss->s_next;
1080                 /* validate base */
1081                 fc.fss = ss;
1082                 fc.fbase = 0;
1083                 fc.fscope = 0;
1084
1085                 /* If the base of the search is missing, signal a refresh */
1086                 rc = syncprov_findbase( op, &fc );
1087                 if ( rc != LDAP_SUCCESS ) {
1088                         SlapReply rs = {REP_RESULT};
1089                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
1090                                 "search base has changed" );
1091                         sprev->s_next = snext;
1092                         syncprov_drop_psearch( ss, 1 );
1093                         ss = sprev;
1094                         continue;
1095                 }
1096
1097
1098                 /* If we're sending results now, look for this op in old matches */
1099                 if ( !saveit ) {
1100                         syncmatches *old;
1101
1102                         /* Did we modify the search base? */
1103                         if ( dn_match( &op->o_req_ndn, &ss->s_base )) {
1104                                 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1105                                 ss->s_flags |= PS_WROTE_BASE;
1106                                 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1107                         }
1108
1109                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
1110                                 old=sm, sm=sm->sm_next ) {
1111                                 if ( sm->sm_op == ss ) {
1112                                         found = 1;
1113                                         old->sm_next = sm->sm_next;
1114                                         op->o_tmpfree( sm, op->o_tmpmemctx );
1115                                         break;
1116                                 }
1117                         }
1118                 }
1119
1120                 /* check if current o_req_dn is in scope and matches filter */
1121                 if ( fc.fscope && test_filter( op, e, ss->s_op->ors_filter ) ==
1122                         LDAP_COMPARE_TRUE ) {
1123                         if ( saveit ) {
1124                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
1125                                 sm->sm_next = opc->smatches;
1126                                 sm->sm_op = ss;
1127                                 ss->s_inuse++;
1128                                 opc->smatches = sm;
1129                         } else {
1130                                 /* if found send UPDATE else send ADD */
1131                                 ss->s_inuse++;
1132                                 syncprov_qresp( opc, ss,
1133                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD );
1134                                 ss->s_inuse--;
1135                         }
1136                 } else if ( !saveit && found ) {
1137                         /* send DELETE */
1138                         syncprov_qresp( opc, ss, LDAP_SYNC_DELETE );
1139                 }
1140         }
1141         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1142
1143         if ( op->o_tag != LDAP_REQ_ADD && e ) {
1144                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1145                 be_entry_release_rw( op, e, 0 );
1146                 op->o_bd->bd_info = (BackendInfo *)on;
1147         }
1148         if ( freefdn ) {
1149                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
1150         }
1151 }
1152
1153 static int
1154 syncprov_op_cleanup( Operation *op, SlapReply *rs )
1155 {
1156         slap_callback *cb = op->o_callback;
1157         opcookie *opc = cb->sc_private;
1158         slap_overinst *on = opc->son;
1159         syncprov_info_t         *si = on->on_bi.bi_private;
1160         syncmatches *sm, *snext;
1161         modtarget *mt, mtdummy;
1162
1163         for (sm = opc->smatches; sm; sm=snext) {
1164                 snext = sm->sm_next;
1165                 syncprov_free_syncop( sm->sm_op );
1166                 op->o_tmpfree( sm, op->o_tmpmemctx );
1167         }
1168
1169         /* Remove op from lock table */
1170         mtdummy.mt_op = op;
1171         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1172         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1173         if ( mt ) {
1174                 modinst *mi = mt->mt_mods;
1175
1176                 /* If there are more, promote the next one */
1177                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1178                 if ( mi->mi_next ) {
1179                         mt->mt_mods = mi->mi_next;
1180                         mt->mt_op = mt->mt_mods->mi_op;
1181                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1182                 } else {
1183                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
1184                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1185                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1186                         ch_free( mt );
1187                 }
1188         }
1189         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1190         if ( !BER_BVISNULL( &opc->suuid ))
1191                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1192         if ( !BER_BVISNULL( &opc->sndn ))
1193                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1194         if ( !BER_BVISNULL( &opc->sdn ))
1195                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1196         op->o_callback = cb->sc_next;
1197         op->o_tmpfree(cb, op->o_tmpmemctx);
1198
1199         return 0;
1200 }
1201
1202 static void
1203 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1204 {
1205         syncprov_info_t         *si = on->on_bi.bi_private;
1206         Modifications mod;
1207         Operation opm;
1208         struct berval bv[2];
1209         slap_callback cb = {0};
1210         int manage = get_manageDSAit(op);
1211
1212         mod.sml_values = bv;
1213         bv[1].bv_val = NULL;
1214         bv[0] = si->si_ctxcsn;
1215         mod.sml_nvalues = NULL;
1216         mod.sml_desc = slap_schema.si_ad_contextCSN;
1217         mod.sml_op = LDAP_MOD_REPLACE;
1218         mod.sml_flags = 0;
1219         mod.sml_next = NULL;
1220
1221         cb.sc_response = slap_null_cb;
1222         opm = *op;
1223         opm.o_tag = LDAP_REQ_MODIFY;
1224         opm.o_callback = &cb;
1225         opm.orm_modlist = &mod;
1226         opm.o_req_dn = op->o_bd->be_suffix[0];
1227         opm.o_req_ndn = op->o_bd->be_nsuffix[0];
1228         opm.o_bd->bd_info = on->on_info->oi_orig;
1229         opm.o_managedsait = SLAP_CONTROL_NONCRITICAL;
1230         opm.o_bd->be_modify( &opm, rs );
1231         opm.o_managedsait = manage;
1232 }
1233
1234 static void
1235 syncprov_add_slog( Operation *op, struct berval *csn )
1236 {
1237         opcookie *opc = op->o_callback->sc_private;
1238         slap_overinst *on = opc->son;
1239         syncprov_info_t         *si = on->on_bi.bi_private;
1240         sessionlog *sl;
1241         slog_entry *se;
1242
1243         sl = si->si_logs;
1244         {
1245                 /* Allocate a record. UUIDs are not NUL-terminated. */
1246                 se = ch_malloc( sizeof( slog_entry ) + opc->suuid.bv_len + 
1247                         csn->bv_len + 1 );
1248                 se->se_next = NULL;
1249                 se->se_tag = op->o_tag;
1250
1251                 se->se_uuid.bv_val = (char *)(se+1);
1252                 AC_MEMCPY( se->se_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1253                 se->se_uuid.bv_len = opc->suuid.bv_len;
1254
1255                 se->se_csn.bv_val = se->se_uuid.bv_val + opc->suuid.bv_len;
1256                 AC_MEMCPY( se->se_csn.bv_val, csn->bv_val, csn->bv_len );
1257                 se->se_csn.bv_val[csn->bv_len] = '\0';
1258                 se->se_csn.bv_len = csn->bv_len;
1259
1260                 ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
1261                 if ( sl->sl_head ) {
1262                         sl->sl_tail->se_next = se;
1263                 } else {
1264                         sl->sl_head = se;
1265                 }
1266                 sl->sl_tail = se;
1267                 sl->sl_num++;
1268                 while ( sl->sl_num > sl->sl_size ) {
1269                         se = sl->sl_head;
1270                         sl->sl_head = se->se_next;
1271                         strcpy( sl->sl_mincsn.bv_val, se->se_csn.bv_val );
1272                         sl->sl_mincsn.bv_len = se->se_csn.bv_len;
1273                         ch_free( se );
1274                         sl->sl_num--;
1275                         if ( !sl->sl_head ) {
1276                                 sl->sl_tail = NULL;
1277                         }
1278                 }
1279                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1280         }
1281 }
1282
1283 /* Just set a flag if we found the matching entry */
1284 static int
1285 playlog_cb( Operation *op, SlapReply *rs )
1286 {
1287         if ( rs->sr_type == REP_SEARCH ) {
1288                 op->o_callback->sc_private = (void *)1;
1289         }
1290         return rs->sr_err;
1291 }
1292
1293 /* enter with sl->sl_mutex locked, release before returning */
1294 static void
1295 syncprov_playlog( Operation *op, SlapReply *rs, sessionlog *sl,
1296         struct berval *oldcsn, struct berval *ctxcsn )
1297 {
1298         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1299         slog_entry *se;
1300         int i, j, ndel, num, nmods, mmods;
1301         BerVarray uuids;
1302
1303         if ( !sl->sl_num ) {
1304                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1305                 return;
1306         }
1307
1308         num = sl->sl_num;
1309         i = 0;
1310         nmods = 0;
1311
1312         uuids = op->o_tmpalloc( (num+1) * sizeof( struct berval ) +
1313                 num * UUID_LEN, op->o_tmpmemctx );
1314
1315         uuids[0].bv_val = (char *)(uuids + num + 1);
1316
1317         /* Make a copy of the relevant UUIDs. Put the Deletes up front
1318          * and everything else at the end. Do this first so we can
1319          * unlock the list mutex.
1320          */
1321         for ( se=sl->sl_head; se; se=se->se_next ) {
1322                 if ( ber_bvcmp( &se->se_csn, oldcsn ) < 0 ) continue;
1323                 if ( ber_bvcmp( &se->se_csn, ctxcsn ) > 0 ) break;
1324                 if ( se->se_tag == LDAP_REQ_DELETE ) {
1325                         j = i;
1326                         i++;
1327                 } else {
1328                         nmods++;
1329                         j = num - nmods;
1330                 }
1331                 uuids[j].bv_val = uuids[0].bv_val + (j * UUID_LEN);
1332                 AC_MEMCPY(uuids[j].bv_val, se->se_uuid.bv_val, UUID_LEN);
1333                 uuids[j].bv_len = UUID_LEN;
1334         }
1335         ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1336
1337         ndel = i;
1338
1339         /* Zero out unused slots */
1340         for ( i=ndel; i < num - nmods; i++ )
1341                 uuids[i].bv_len = 0;
1342
1343         /* Mods must be validated to see if they belong in this delete set.
1344          */
1345
1346         mmods = nmods;
1347         /* Strip any duplicates */
1348         for ( i=0; i<nmods; i++ ) {
1349                 for ( j=0; j<ndel; j++ ) {
1350                         if ( bvmatch( &uuids[j], &uuids[num - 1 - i] )) {
1351                                 uuids[num - 1 - i].bv_len = 0;
1352                                 mmods --;
1353                                 break;
1354                         }
1355                 }
1356                 if ( uuids[num - 1 - i].bv_len == 0 ) continue;
1357                 for ( j=0; j<i; j++ ) {
1358                         if ( bvmatch( &uuids[num - 1 - j], &uuids[num - 1 - i] )) {
1359                                 uuids[num - 1 - i].bv_len = 0;
1360                                 mmods --;
1361                                 break;
1362                         }
1363                 }
1364         }
1365
1366         if ( mmods ) {
1367                 Operation fop;
1368                 SlapReply frs = { REP_RESULT };
1369                 int rc;
1370                 Filter mf, af;
1371 #ifdef LDAP_COMP_MATCH
1372                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
1373 #else
1374                 AttributeAssertion eq;
1375 #endif
1376                 slap_callback cb = {0};
1377
1378                 fop = *op;
1379
1380                 fop.o_sync_mode = 0;
1381                 fop.o_callback = &cb;
1382                 fop.ors_limit = NULL;
1383                 fop.ors_tlimit = SLAP_NO_LIMIT;
1384                 fop.ors_attrs = slap_anlist_all_attributes;
1385                 fop.ors_attrsonly = 0;
1386                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
1387
1388                 af.f_choice = LDAP_FILTER_AND;
1389                 af.f_next = NULL;
1390                 af.f_and = &mf;
1391                 mf.f_choice = LDAP_FILTER_EQUALITY;
1392                 mf.f_ava = &eq;
1393                 mf.f_av_desc = slap_schema.si_ad_entryUUID;
1394                 mf.f_next = fop.ors_filter;
1395
1396                 fop.ors_filter = &af;
1397
1398                 cb.sc_response = playlog_cb;
1399                 fop.o_bd->bd_info = on->on_info->oi_orig;
1400
1401                 for ( i=ndel; i<num; i++ ) {
1402                         if ( uuids[i].bv_len == 0 ) continue;
1403
1404                         mf.f_av_value = uuids[i];
1405                         cb.sc_private = NULL;
1406                         fop.ors_slimit = 1;
1407                         rc = fop.o_bd->be_search( &fop, &frs );
1408
1409                         /* If entry was not found, add to delete list */
1410                         if ( !cb.sc_private ) {
1411                                 uuids[ndel++] = uuids[i];
1412                         }
1413                 }
1414                 fop.o_bd->bd_info = (BackendInfo *)on;
1415         }
1416         if ( ndel ) {
1417                 uuids[ndel].bv_val = NULL;
1418                 syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL, 0, uuids, 1 );
1419         }
1420 }
1421
1422 static int
1423 syncprov_op_response( Operation *op, SlapReply *rs )
1424 {
1425         opcookie *opc = op->o_callback->sc_private;
1426         slap_overinst *on = opc->son;
1427         syncprov_info_t         *si = on->on_bi.bi_private;
1428         syncmatches *sm;
1429
1430         if ( rs->sr_err == LDAP_SUCCESS )
1431         {
1432                 struct berval maxcsn = BER_BVNULL, curcsn = BER_BVNULL;
1433                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1434
1435                 /* Update our context CSN */
1436                 cbuf[0] = '\0';
1437                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1438                 slap_get_commit_csn( op, &maxcsn, &curcsn );
1439                 if ( !BER_BVISNULL( &maxcsn ) ) {
1440                         strcpy( cbuf, maxcsn.bv_val );
1441                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn ) > 0 ) {
1442                                 strcpy( si->si_ctxcsnbuf, cbuf );
1443                                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
1444                         }
1445                 }
1446
1447                 /* Don't do any processing for consumer contextCSN updates */
1448                 if ( SLAP_SYNC_SHADOW( op->o_bd ) && 
1449                         op->o_msgid == SLAP_SYNC_UPDATE_MSGID ) {
1450                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1451                         return SLAP_CB_CONTINUE;
1452                 }
1453
1454                 si->si_numops++;
1455                 if ( si->si_chkops || si->si_chktime ) {
1456                         int do_check=0;
1457                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1458                                 do_check = 1;
1459                                 si->si_numops = 0;
1460                         }
1461                         if ( si->si_chktime &&
1462                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1463                                 do_check = 1;
1464                                 si->si_chklast = op->o_time;
1465                         }
1466                         if ( do_check ) {
1467                                 syncprov_checkpoint( op, rs, on );
1468                         }
1469                 }
1470                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1471
1472                 opc->sctxcsn.bv_len = maxcsn.bv_len;
1473                 opc->sctxcsn.bv_val = cbuf;
1474
1475                 /* Handle any persistent searches */
1476                 if ( si->si_ops ) {
1477                         switch(op->o_tag) {
1478                         case LDAP_REQ_ADD:
1479                         case LDAP_REQ_MODIFY:
1480                         case LDAP_REQ_MODRDN:
1481                         case LDAP_REQ_EXTENDED:
1482                                 syncprov_matchops( op, opc, 0 );
1483                                 break;
1484                         case LDAP_REQ_DELETE:
1485                                 /* for each match in opc->smatches:
1486                                  *   send DELETE msg
1487                                  */
1488                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1489                                         if ( sm->sm_op->s_op->o_abandon )
1490                                                 continue;
1491                                         syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_DELETE );
1492                                 }
1493                                 break;
1494                         }
1495                 }
1496
1497                 /* Add any log records */
1498                 if ( si->si_logs && op->o_tag != LDAP_REQ_ADD ) {
1499                         syncprov_add_slog( op, &curcsn );
1500                 }
1501
1502         }
1503         return SLAP_CB_CONTINUE;
1504 }
1505
1506 /* We don't use a subentry to store the context CSN any more.
1507  * We expose the current context CSN as an operational attribute
1508  * of the suffix entry.
1509  */
1510 static int
1511 syncprov_op_compare( Operation *op, SlapReply *rs )
1512 {
1513         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1514         syncprov_info_t         *si = on->on_bi.bi_private;
1515         int rc = SLAP_CB_CONTINUE;
1516
1517         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1518                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1519         {
1520                 Entry e = {0};
1521                 Attribute a = {0};
1522                 struct berval bv[2];
1523
1524                 e.e_name = op->o_bd->be_suffix[0];
1525                 e.e_nname = op->o_bd->be_nsuffix[0];
1526
1527                 BER_BVZERO( &bv[1] );
1528                 bv[0] = si->si_ctxcsn;
1529
1530                 a.a_desc = slap_schema.si_ad_contextCSN;
1531                 a.a_vals = bv;
1532                 a.a_nvals = a.a_vals;
1533
1534                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1535
1536                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1537                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1538                 if ( ! rs->sr_err ) {
1539                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1540                         goto return_results;
1541                 }
1542
1543                 if ( get_assert( op ) &&
1544                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1545                 {
1546                         rs->sr_err = LDAP_ASSERTION_FAILED;
1547                         goto return_results;
1548                 }
1549
1550
1551                 rs->sr_err = LDAP_COMPARE_FALSE;
1552
1553                 if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
1554                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1555                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1556                                 a.a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
1557                 {
1558                         rs->sr_err = LDAP_COMPARE_TRUE;
1559                 }
1560
1561 return_results:;
1562
1563                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1564
1565                 send_ldap_result( op, rs );
1566
1567                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1568                         rs->sr_err = LDAP_SUCCESS;
1569                 }
1570                 rc = rs->sr_err;
1571         }
1572
1573         return rc;
1574 }
1575
1576 static int
1577 syncprov_op_mod( Operation *op, SlapReply *rs )
1578 {
1579         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1580         syncprov_info_t         *si = on->on_bi.bi_private;
1581
1582         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+
1583                 sizeof(opcookie) +
1584                 (si->si_ops ? sizeof(modinst) : 0 ),
1585                 op->o_tmpmemctx);
1586         opcookie *opc = (opcookie *)(cb+1);
1587         opc->son = on;
1588         cb->sc_response = syncprov_op_response;
1589         cb->sc_cleanup = syncprov_op_cleanup;
1590         cb->sc_private = opc;
1591         cb->sc_next = op->o_callback;
1592         op->o_callback = cb;
1593
1594         /* If there are active persistent searches, lock this operation.
1595          * See seqmod.c for the locking logic on its own.
1596          */
1597         if ( si->si_ops ) {
1598                 modtarget *mt, mtdummy;
1599                 modinst *mi;
1600
1601                 mi = (modinst *)(opc+1);
1602                 mi->mi_op = op;
1603
1604                 /* See if we're already modifying this entry... */
1605                 mtdummy.mt_op = op;
1606                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1607                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1608                 if ( mt ) {
1609                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1610                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1611                         mt->mt_tail->mi_next = mi;
1612                         mt->mt_tail = mi;
1613                         /* wait for this op to get to head of list */
1614                         while ( mt->mt_mods != mi ) {
1615                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1616                                 ldap_pvt_thread_yield();
1617                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1618
1619                                 /* clean up if the caller is giving up */
1620                                 if ( op->o_abandon ) {
1621                                         modinst *m2;
1622                                         for ( m2 = mt->mt_mods; m2->mi_next != mi;
1623                                                 m2 = m2->mi_next );
1624                                         m2->mi_next = mi->mi_next;
1625                                         if ( mt->mt_tail == mi ) mt->mt_tail = m2;
1626                                         op->o_tmpfree( cb, op->o_tmpmemctx );
1627                                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1628                                         return SLAPD_ABANDON;
1629                                 }
1630                         }
1631                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1632                 } else {
1633                         /* Record that we're modifying this entry now */
1634                         mt = ch_malloc( sizeof(modtarget) );
1635                         mt->mt_mods = mi;
1636                         mt->mt_tail = mi;
1637                         mt->mt_op = mi->mi_op;
1638                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1639                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1640                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1641                 }
1642         }
1643
1644         if (( si->si_ops || si->si_logs ) && op->o_tag != LDAP_REQ_ADD )
1645                 syncprov_matchops( op, opc, 1 );
1646
1647         return SLAP_CB_CONTINUE;
1648 }
1649
1650 static int
1651 syncprov_op_extended( Operation *op, SlapReply *rs )
1652 {
1653         if ( exop_is_write( op ))
1654                 return syncprov_op_mod( op, rs );
1655
1656         return SLAP_CB_CONTINUE;
1657 }
1658
1659 typedef struct searchstate {
1660         slap_overinst *ss_on;
1661         syncops *ss_so;
1662         int ss_present;
1663         struct berval ss_ctxcsn;
1664         char ss_csnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1665 } searchstate;
1666
1667 static int
1668 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1669 {
1670         if ( rs->sr_ctrls ) {
1671                 op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
1672                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1673                 rs->sr_ctrls = NULL;
1674         }
1675         return 0;
1676 }
1677
1678 static void
1679 syncprov_detach_op( Operation *op, syncops *so, slap_overinst *on )
1680 {
1681         Operation *op2;
1682         int i, alen = 0;
1683         size_t size;
1684         char *ptr;
1685         GroupAssertion *g1, *g2;
1686
1687         /* count the search attrs */
1688         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1689                 alen += op->ors_attrs[i].an_name.bv_len + 1;
1690         }
1691         /* Make a new copy of the operation */
1692         size = sizeof(Operation) + sizeof(Opheader) +
1693                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
1694                 op->o_req_dn.bv_len + 1 +
1695                 op->o_req_ndn.bv_len + 1 +
1696                 op->o_ndn.bv_len + 1 +
1697                 so->s_filterstr.bv_len + 1;
1698         op2 = (Operation *)ch_calloc( 1, size );
1699         op2->o_hdr = (Opheader *)(op2+1);
1700
1701         /* Copy the fields we care about explicitly, leave the rest alone */
1702         *op2->o_hdr = *op->o_hdr;
1703         op2->o_tag = op->o_tag;
1704         op2->o_time = op->o_time;
1705         op2->o_bd = on->on_info->oi_origdb;
1706         op2->o_request = op->o_request;
1707         op2->o_private = on;
1708
1709         if ( i ) {
1710                 op2->ors_attrs = (AttributeName *)(op2->o_hdr + 1);
1711                 ptr = (char *)(op2->ors_attrs+i+1);
1712                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1713                         op2->ors_attrs[i] = op->ors_attrs[i];
1714                         op2->ors_attrs[i].an_name.bv_val = ptr;
1715                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
1716                 }
1717                 BER_BVZERO( &op2->ors_attrs[i].an_name );
1718         } else {
1719                 ptr = (char *)(op2->o_hdr + 1);
1720         }
1721         op2->o_authz = op->o_authz;
1722         op2->o_ndn.bv_val = ptr;
1723         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
1724         op2->o_dn = op2->o_ndn;
1725         op2->o_req_dn.bv_len = op->o_req_dn.bv_len;
1726         op2->o_req_dn.bv_val = ptr;
1727         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
1728         op2->o_req_ndn.bv_len = op->o_req_ndn.bv_len;
1729         op2->o_req_ndn.bv_val = ptr;
1730         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
1731         op2->ors_filterstr.bv_val = ptr;
1732         strcpy( ptr, so->s_filterstr.bv_val );
1733         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
1734         op2->ors_filter = str2filter( ptr );
1735         so->s_op = op2;
1736
1737         /* Copy any cached group ACLs individually */
1738         op2->o_groups = NULL;
1739         for ( g1=op->o_groups; g1; g1=g1->ga_next ) {
1740                 g2 = ch_malloc( sizeof(GroupAssertion) + g1->ga_len );
1741                 *g2 = *g1;
1742                 strcpy( g2->ga_ndn, g1->ga_ndn );
1743                 g2->ga_next = op2->o_groups;
1744                 op2->o_groups = g2;
1745         }
1746         /* Don't allow any further group caching */
1747         op2->o_do_not_cache = 1;
1748
1749         /* Add op2 to conn so abandon will find us */
1750         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1751         op->o_conn->c_n_ops_executing++;
1752         op->o_conn->c_n_ops_completed--;
1753         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op2, o_next );
1754         so->s_flags |= PS_IS_DETACHED;
1755         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1756 }
1757
1758 static int
1759 syncprov_search_response( Operation *op, SlapReply *rs )
1760 {
1761         searchstate *ss = op->o_callback->sc_private;
1762         slap_overinst *on = ss->ss_on;
1763         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
1764
1765         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
1766                 Attribute *a;
1767                 /* If we got a referral without a referral object, there's
1768                  * something missing that we cannot replicate. Just ignore it.
1769                  * The consumer will abort because we didn't send the expected
1770                  * control.
1771                  */
1772                 if ( !rs->sr_entry ) {
1773                         assert( rs->sr_entry != NULL );
1774                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
1775                         return SLAP_CB_CONTINUE;
1776                 }
1777                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryCSN );
1778                 if ( a ) {
1779                         /* Make sure entry is less than the snaphot'd contextCSN */
1780                         if ( ber_bvcmp( &a->a_nvals[0], &ss->ss_ctxcsn ) > 0 )
1781                                 return LDAP_SUCCESS;
1782
1783                         /* Don't send the ctx entry twice */
1784                         if ( !BER_BVISNULL( &srs->sr_state.ctxcsn ) &&
1785                                 bvmatch( &a->a_nvals[0], &srs->sr_state.ctxcsn ) )
1786                                 return LDAP_SUCCESS;
1787                 }
1788                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1789                         op->o_tmpmemctx );
1790                 rs->sr_ctrls[1] = NULL;
1791                 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
1792                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
1793         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
1794                 struct berval cookie;
1795
1796                 slap_compose_sync_cookie( op, &cookie, &ss->ss_ctxcsn,
1797                         srs->sr_state.rid );
1798
1799                 /* Is this a regular refresh? */
1800                 if ( !ss->ss_so ) {
1801                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1802                                 op->o_tmpmemctx );
1803                         rs->sr_ctrls[1] = NULL;
1804                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
1805                                 0, 1, &cookie, ss->ss_present ?  LDAP_SYNC_REFRESH_PRESENTS :
1806                                         LDAP_SYNC_REFRESH_DELETES );
1807                 } else {
1808                 /* It's RefreshAndPersist, transition to Persist phase */
1809                         syncprov_sendinfo( op, rs, ( ss->ss_present && rs->sr_nentries ) ?
1810                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
1811                                 &cookie, 1, NULL, 0 );
1812                         /* Flush any queued persist messages */
1813                         if ( ss->ss_so->s_res ) {
1814                                 syncprov_qplay( op, on, ss->ss_so );
1815                         }
1816
1817                         /* Detach this Op from frontend control */
1818                         ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
1819
1820                         /* Turn off the refreshing flag */
1821                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
1822
1823                         syncprov_detach_op( op, ss->ss_so, on );
1824                         ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
1825
1826                         return LDAP_SUCCESS;
1827                 }
1828         }
1829
1830         return SLAP_CB_CONTINUE;
1831 }
1832
1833 static int
1834 syncprov_op_search( Operation *op, SlapReply *rs )
1835 {
1836         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1837         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1838         slap_callback   *cb;
1839         int gotstate = 0, nochange = 0, do_present;
1840         syncops *sop = NULL;
1841         searchstate *ss;
1842         sync_control *srs;
1843         struct berval ctxcsn;
1844         char csnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1845
1846         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
1847
1848         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1849                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
1850                 return rs->sr_err;
1851         }
1852
1853         do_present = si->si_nopres ? 0 : 1;
1854
1855         srs = op->o_controls[slap_cids.sc_LDAPsync];
1856         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1857
1858         /* If this is a persistent search, set it up right away */
1859         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
1860                 syncops so = {0};
1861                 fbase_cookie fc;
1862                 opcookie opc;
1863                 slap_callback sc;
1864
1865                 fc.fss = &so;
1866                 fc.fbase = 0;
1867                 so.s_eid = NOID;
1868                 so.s_op = op;
1869                 so.s_flags = PS_IS_REFRESHING | PS_FIND_BASE;
1870                 /* syncprov_findbase expects to be called as a callback... */
1871                 sc.sc_private = &opc;
1872                 opc.son = on;
1873                 cb = op->o_callback;
1874                 op->o_callback = &sc;
1875                 rs->sr_err = syncprov_findbase( op, &fc );
1876                 op->o_callback = cb;
1877
1878                 if ( rs->sr_err != LDAP_SUCCESS ) {
1879                         send_ldap_result( op, rs );
1880                         return rs->sr_err;
1881                 }
1882                 sop = ch_malloc( sizeof( syncops ));
1883                 *sop = so;
1884                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
1885                 sop->s_rid = srs->sr_state.rid;
1886                 sop->s_inuse = 1;
1887
1888                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1889                 sop->s_next = si->si_ops;
1890                 si->si_ops = sop;
1891                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1892         }
1893
1894         /* snapshot the ctxcsn */
1895         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1896         strcpy( csnbuf, si->si_ctxcsnbuf );
1897         ctxcsn.bv_len = si->si_ctxcsn.bv_len;
1898         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1899         ctxcsn.bv_val = csnbuf;
1900         
1901         /* If we have a cookie, handle the PRESENT lookups */
1902         if ( !BER_BVISNULL( &srs->sr_state.ctxcsn )) {
1903                 sessionlog *sl;
1904
1905                 /* The cookie was validated when it was parsed, just use it */
1906
1907                 /* If just Refreshing and nothing has changed, shortcut it */
1908                 if ( bvmatch( &srs->sr_state.ctxcsn, &ctxcsn )) {
1909                         nochange = 1;
1910                         if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
1911                                 LDAPControl     *ctrls[2];
1912
1913                                 ctrls[0] = NULL;
1914                                 ctrls[1] = NULL;
1915                                 syncprov_done_ctrl( op, rs, ctrls, 0, 0,
1916                                         NULL, LDAP_SYNC_REFRESH_DELETES );
1917                                 rs->sr_ctrls = ctrls;
1918                                 rs->sr_err = LDAP_SUCCESS;
1919                                 send_ldap_result( op, rs );
1920                                 rs->sr_ctrls = NULL;
1921                                 return rs->sr_err;
1922                         }
1923                         goto shortcut;
1924                 }
1925                 /* Do we have a sessionlog for this search? */
1926                 sl=si->si_logs;
1927                 if ( sl ) {
1928                         ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
1929                         if ( ber_bvcmp( &srs->sr_state.ctxcsn, &sl->sl_mincsn ) >= 0 ) {
1930                                 do_present = 0;
1931                                 /* mutex is unlocked in playlog */
1932                                 syncprov_playlog( op, rs, sl, &srs->sr_state.ctxcsn, &ctxcsn );
1933                         } else {
1934                                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1935                         }
1936                 }
1937                 /* Is the CSN still present in the database? */
1938                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
1939                         /* No, so a reload is required */
1940 #if 0           /* the consumer doesn't seem to send this hint */
1941                         if ( op->o_sync_rhint == 0 ) {
1942                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
1943                                 return rs->sr_err;
1944                         }
1945 #endif
1946                 } else {
1947                         gotstate = 1;
1948                         /* If changed and doing Present lookup, send Present UUIDs */
1949                         if ( do_present && syncprov_findcsn( op, FIND_PRESENT ) !=
1950                                 LDAP_SUCCESS ) {
1951                                 send_ldap_result( op, rs );
1952                                 return rs->sr_err;
1953                         }
1954                 }
1955         }
1956
1957 shortcut:
1958         /* Append CSN range to search filter, save original filter
1959          * for persistent search evaluation
1960          */
1961         if ( sop ) {
1962                 sop->s_filterstr= op->ors_filterstr;
1963         }
1964
1965         /* If something changed, find the changes */
1966         if ( gotstate && !nochange ) {
1967                 Filter *fand, *fava;
1968
1969                 fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1970                 fand->f_choice = LDAP_FILTER_AND;
1971                 fand->f_next = NULL;
1972                 fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1973                 fand->f_and = fava;
1974                 fava->f_choice = LDAP_FILTER_GE;
1975                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1976                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1977 #ifdef LDAP_COMP_MATCH
1978                 fava->f_ava->aa_cf = NULL;
1979 #endif
1980                 ber_dupbv_x( &fava->f_ava->aa_value, &srs->sr_state.ctxcsn, op->o_tmpmemctx );
1981                 fava->f_next = op->ors_filter;
1982                 op->ors_filter = fand;
1983                 filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1984         }
1985
1986         /* Let our callback add needed info to returned entries */
1987         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1988         ss = (searchstate *)(cb+1);
1989         ss->ss_on = on;
1990         ss->ss_so = sop;
1991         ss->ss_present = do_present;
1992         ss->ss_ctxcsn.bv_len = ctxcsn.bv_len;
1993         ss->ss_ctxcsn.bv_val = ss->ss_csnbuf;
1994         strcpy( ss->ss_ctxcsn.bv_val, ctxcsn.bv_val );
1995         cb->sc_response = syncprov_search_response;
1996         cb->sc_cleanup = syncprov_search_cleanup;
1997         cb->sc_private = ss;
1998         cb->sc_next = op->o_callback;
1999         op->o_callback = cb;
2000
2001 #if 0   /* I don't think we need to shortcircuit back-bdb any more */
2002         op->o_sync_mode &= SLAP_CONTROL_MASK;
2003 #endif
2004
2005         /* If this is a persistent search and no changes were reported during
2006          * the refresh phase, just invoke the response callback to transition
2007          * us into persist phase
2008          */
2009         if ( nochange ) {
2010                 rs->sr_err = LDAP_SUCCESS;
2011                 rs->sr_nentries = 0;
2012                 send_ldap_result( op, rs );
2013                 return rs->sr_err;
2014         }
2015         return SLAP_CB_CONTINUE;
2016 }
2017
2018 static int
2019 syncprov_operational(
2020         Operation *op,
2021         SlapReply *rs )
2022 {
2023         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
2024         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2025
2026         if ( rs->sr_entry &&
2027                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
2028
2029                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
2030                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
2031                         Attribute *a, **ap = NULL;
2032
2033                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
2034                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
2035                                         break;
2036                         }
2037
2038                         if ( !a ) {
2039                                 for ( ap = &rs->sr_operational_attrs; *ap; ap=&(*ap)->a_next );
2040
2041                                 a = ch_malloc( sizeof(Attribute));
2042                                 a->a_desc = slap_schema.si_ad_contextCSN;
2043                                 a->a_vals = ch_malloc( 2 * sizeof(struct berval));
2044                                 a->a_vals[1].bv_val = NULL;
2045                                 a->a_nvals = a->a_vals;
2046                                 a->a_next = NULL;
2047                                 a->a_flags = 0;
2048                                 *ap = a;
2049                         }
2050
2051                         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
2052                         if ( !ap ) {
2053                                 strcpy( a->a_vals[0].bv_val, si->si_ctxcsnbuf );
2054                         } else {
2055                                 ber_dupbv( &a->a_vals[0], &si->si_ctxcsn );
2056                         }
2057                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
2058                 }
2059         }
2060         return SLAP_CB_CONTINUE;
2061 }
2062
2063 enum {
2064         SP_CHKPT = 1,
2065         SP_SESSL,
2066         SP_NOPRES
2067 };
2068
2069 static ConfigDriver sp_cf_gen;
2070
2071 static ConfigTable spcfg[] = {
2072         { "syncprov-checkpoint", "ops> <minutes", 3, 3, 0, ARG_MAGIC|SP_CHKPT,
2073                 sp_cf_gen, "( OLcfgOvAt:1.1 NAME 'olcSpCheckpoint' "
2074                         "DESC 'ContextCSN checkpoint interval in ops and minutes' "
2075                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2076         { "syncprov-sessionlog", "ops", 2, 2, 0, ARG_INT|ARG_MAGIC|SP_SESSL,
2077                 sp_cf_gen, "( OLcfgOvAt:1.2 NAME 'olcSpSessionlog' "
2078                         "DESC 'Session log size in ops' "
2079                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
2080         { "syncprov-nopresent", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_NOPRES,
2081                 sp_cf_gen, "( OLcfgOvAt:1.3 NAME 'olcSpNoPresent' "
2082                         "DESC 'Omit Present phase processing' "
2083                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
2084         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2085 };
2086
2087 static ConfigOCs spocs[] = {
2088         { "( OLcfgOvOc:1.1 "
2089                 "NAME 'olcSyncProvConfig' "
2090                 "DESC 'SyncRepl Provider configuration' "
2091                 "SUP olcOverlayConfig "
2092                 "MAY ( olcSpCheckpoint $ olcSpSessionlog $ olcSpNoPresent ) )",
2093                         Cft_Overlay, spcfg },
2094         { NULL, 0, NULL }
2095 };
2096
2097 static int
2098 sp_cf_gen(ConfigArgs *c)
2099 {
2100         slap_overinst           *on = (slap_overinst *)c->bi;
2101         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2102         int rc = 0;
2103
2104         if ( c->op == SLAP_CONFIG_EMIT ) {
2105                 switch ( c->type ) {
2106                 case SP_CHKPT:
2107                         if ( si->si_chkops || si->si_chktime ) {
2108                                 struct berval bv;
2109                                 bv.bv_len = sprintf( c->msg, "%d %d",
2110                                         si->si_chkops, si->si_chktime );
2111                                 bv.bv_val = c->msg;
2112                                 value_add_one( &c->rvalue_vals, &bv );
2113                         } else {
2114                                 rc = 1;
2115                         }
2116                         break;
2117                 case SP_SESSL:
2118                         if ( si->si_logs ) {
2119                                 c->value_int = si->si_logs->sl_size;
2120                         } else {
2121                                 rc = 1;
2122                         }
2123                         break;
2124                 case SP_NOPRES:
2125                         if ( si->si_nopres ) {
2126                                 c->value_int = 1;
2127                         } else {
2128                                 rc = 1;
2129                         }
2130                         break;
2131                 }
2132                 return rc;
2133         } else if ( c->op == LDAP_MOD_DELETE ) {
2134                 switch ( c->type ) {
2135                 case SP_CHKPT:
2136                         si->si_chkops = 0;
2137                         si->si_chktime = 0;
2138                         break;
2139                 case SP_SESSL:
2140                         if ( si->si_logs )
2141                                 si->si_logs->sl_size = 0;
2142                         else
2143                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2144                         break;
2145                 case SP_NOPRES:
2146                         if ( si->si_nopres )
2147                                 si->si_nopres = 0;
2148                         else
2149                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2150                         break;
2151                 }
2152                 return rc;
2153         }
2154         switch ( c->type ) {
2155         case SP_CHKPT:
2156                 si->si_chkops = atoi( c->argv[1] );
2157                 si->si_chktime = atoi( c->argv[2] ) * 60;
2158                 break;
2159         case SP_SESSL: {
2160                 sessionlog *sl;
2161                 int size = c->value_int;
2162
2163                 if ( size < 0 ) {
2164                         sprintf( c->msg, "%s size %d is negative",
2165                                 c->argv[0], size );
2166                         Debug( LDAP_DEBUG_CONFIG, "%s: %s\n", c->log, c->msg, 0 );
2167                         return ARG_BAD_CONF;
2168                 }
2169                 sl = si->si_logs;
2170                 if ( !sl ) {
2171                         sl = ch_malloc( sizeof( sessionlog ) + LDAP_LUTIL_CSNSTR_BUFSIZE );
2172                         sl->sl_mincsn.bv_val = (char *)(sl+1);
2173                         sl->sl_mincsn.bv_len = 0;
2174                         sl->sl_num = 0;
2175                         sl->sl_head = sl->sl_tail = NULL;
2176                         ldap_pvt_thread_mutex_init( &sl->sl_mutex );
2177                         si->si_logs = sl;
2178                 }
2179                 sl->sl_size = size;
2180                 }
2181                 break;
2182         case SP_NOPRES:
2183                 si->si_nopres = c->value_int;
2184                 break;
2185         }
2186         return rc;
2187 }
2188
2189 /* ITS#3456 we cannot run this search on the main thread, must use a
2190  * child thread in order to insure we have a big enough stack.
2191  */
2192 static void *
2193 syncprov_db_otask(
2194         void *ptr
2195 )
2196 {
2197         syncprov_findcsn( ptr, FIND_MAXCSN );
2198         return NULL;
2199 }
2200
2201 /* Read any existing contextCSN from the underlying db.
2202  * Then search for any entries newer than that. If no value exists,
2203  * just generate it. Cache whatever result.
2204  */
2205 static int
2206 syncprov_db_open(
2207     BackendDB *be
2208 )
2209 {
2210         slap_overinst   *on = (slap_overinst *) be->bd_info;
2211         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2212
2213         Connection conn;
2214         char opbuf[OPERATION_BUFFER_SIZE];
2215         char ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
2216         Operation *op = (Operation *)opbuf;
2217         Entry *e;
2218         Attribute *a;
2219         int rc;
2220         void *thrctx = NULL;
2221
2222         if ( slapMode & SLAP_TOOL_MODE ) {
2223                 return 0;
2224         }
2225
2226         rc = overlay_register_control( be, LDAP_CONTROL_SYNC );
2227         if ( rc ) {
2228                 return rc;
2229         }
2230
2231         thrctx = ldap_pvt_thread_pool_context();
2232         connection_fake_init( &conn, op, thrctx );
2233         op->o_bd = be;
2234         op->o_dn = be->be_rootdn;
2235         op->o_ndn = be->be_rootndn;
2236
2237         ctxcsnbuf[0] = '\0';
2238
2239         op->o_bd->bd_info = on->on_info->oi_orig;
2240         rc = be_entry_get_rw( op, be->be_nsuffix, NULL,
2241                 slap_schema.si_ad_contextCSN, 0, &e );
2242
2243         if ( e ) {
2244                 ldap_pvt_thread_t tid;
2245
2246                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
2247                 if ( a ) {
2248                         si->si_ctxcsn.bv_len = a->a_nvals[0].bv_len;
2249                         if ( si->si_ctxcsn.bv_len >= sizeof(si->si_ctxcsnbuf ))
2250                                 si->si_ctxcsn.bv_len = sizeof(si->si_ctxcsnbuf)-1;
2251                         strncpy( si->si_ctxcsnbuf, a->a_nvals[0].bv_val,
2252                                 si->si_ctxcsn.bv_len );
2253                         si->si_ctxcsnbuf[si->si_ctxcsn.bv_len] = '\0';
2254                         strcpy( ctxcsnbuf, si->si_ctxcsnbuf );
2255                 }
2256                 be_entry_release_rw( op, e, 0 );
2257                 op->o_bd->bd_info = (BackendInfo *)on;
2258                 op->o_req_dn = be->be_suffix[0];
2259                 op->o_req_ndn = be->be_nsuffix[0];
2260                 op->ors_scope = LDAP_SCOPE_SUBTREE;
2261                 ldap_pvt_thread_create( &tid, 0, syncprov_db_otask, op );
2262                 ldap_pvt_thread_join( tid, NULL );
2263         } else if ( SLAP_SYNC_SHADOW( op->o_bd )) {
2264                 /* If we're also a consumer, and we didn't find the context entry,
2265                  * then don't generate anything, wait for our provider to send it
2266                  * to us.
2267                  */
2268                 goto out;
2269         }
2270
2271         if ( BER_BVISEMPTY( &si->si_ctxcsn ) ) {
2272                 slap_get_csn( op, si->si_ctxcsnbuf, sizeof(si->si_ctxcsnbuf),
2273                                 &si->si_ctxcsn, 0 );
2274         }
2275
2276         /* If our ctxcsn is different from what was read from the root
2277          * entry, make sure we do a checkpoint on close
2278          */
2279         if ( strcmp( si->si_ctxcsnbuf, ctxcsnbuf )) {
2280                 si->si_numops++;
2281         }
2282
2283 out:
2284         op->o_bd->bd_info = (BackendInfo *)on;
2285         ldap_pvt_thread_pool_context_reset( thrctx );
2286         return 0;
2287 }
2288
2289 /* Write the current contextCSN into the underlying db.
2290  */
2291 static int
2292 syncprov_db_close(
2293     BackendDB *be
2294 )
2295 {
2296     slap_overinst   *on = (slap_overinst *) be->bd_info;
2297     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2298
2299         if ( slapMode & SLAP_TOOL_MODE ) {
2300                 return 0;
2301         }
2302         if ( si->si_numops ) {
2303                 Connection conn;
2304                 char opbuf[OPERATION_BUFFER_SIZE];
2305                 Operation *op = (Operation *)opbuf;
2306                 SlapReply rs = {REP_RESULT};
2307                 void *thrctx;
2308
2309                 thrctx = ldap_pvt_thread_pool_context();
2310                 connection_fake_init( &conn, op, thrctx );
2311                 op->o_bd = be;
2312                 op->o_dn = be->be_rootdn;
2313                 op->o_ndn = be->be_rootndn;
2314                 syncprov_checkpoint( op, &rs, on );
2315                 ldap_pvt_thread_pool_context_reset( thrctx );
2316         }
2317
2318     return 0;
2319 }
2320
2321 static int
2322 syncprov_db_init(
2323         BackendDB *be
2324 )
2325 {
2326         slap_overinst   *on = (slap_overinst *)be->bd_info;
2327         syncprov_info_t *si;
2328
2329         si = ch_calloc(1, sizeof(syncprov_info_t));
2330         on->on_bi.bi_private = si;
2331         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
2332         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
2333         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
2334         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
2335
2336         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
2337         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
2338         csn_anlist[1].an_desc = slap_schema.si_ad_entryUUID;
2339         csn_anlist[1].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2340
2341         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
2342         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2343
2344         return 0;
2345 }
2346
2347 static int
2348 syncprov_db_destroy(
2349         BackendDB *be
2350 )
2351 {
2352         slap_overinst   *on = (slap_overinst *)be->bd_info;
2353         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2354
2355         if ( si ) {
2356                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
2357                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
2358                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
2359                 ch_free( si );
2360         }
2361
2362         return 0;
2363 }
2364
2365 static int syncprov_parseCtrl (
2366         Operation *op,
2367         SlapReply *rs,
2368         LDAPControl *ctrl )
2369 {
2370         ber_tag_t tag;
2371         BerElementBuffer berbuf;
2372         BerElement *ber = (BerElement *)&berbuf;
2373         ber_int_t mode;
2374         ber_len_t len;
2375         struct berval cookie = BER_BVNULL;
2376         sync_control *sr;
2377         int rhint = 0;
2378
2379         if ( op->o_sync != SLAP_CONTROL_NONE ) {
2380                 rs->sr_text = "Sync control specified multiple times";
2381                 return LDAP_PROTOCOL_ERROR;
2382         }
2383
2384         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
2385                 rs->sr_text = "Sync control specified with pagedResults control";
2386                 return LDAP_PROTOCOL_ERROR;
2387         }
2388
2389         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
2390                 rs->sr_text = "Sync control value is empty (or absent)";
2391                 return LDAP_PROTOCOL_ERROR;
2392         }
2393
2394         /* Parse the control value
2395          *      syncRequestValue ::= SEQUENCE {
2396          *              mode   ENUMERATED {
2397          *                      -- 0 unused
2398          *                      refreshOnly             (1),
2399          *                      -- 2 reserved
2400          *                      refreshAndPersist       (3)
2401          *              },
2402          *              cookie  syncCookie OPTIONAL
2403          *      }
2404          */
2405
2406         ber_init2( ber, &ctrl->ldctl_value, 0 );
2407
2408         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
2409                 rs->sr_text = "Sync control : mode decoding error";
2410                 return LDAP_PROTOCOL_ERROR;
2411         }
2412
2413         switch( mode ) {
2414         case LDAP_SYNC_REFRESH_ONLY:
2415                 mode = SLAP_SYNC_REFRESH;
2416                 break;
2417         case LDAP_SYNC_REFRESH_AND_PERSIST:
2418                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
2419                 break;
2420         default:
2421                 rs->sr_text = "Sync control : unknown update mode";
2422                 return LDAP_PROTOCOL_ERROR;
2423         }
2424
2425         tag = ber_peek_tag( ber, &len );
2426
2427         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
2428                 if (( ber_scanf( ber, /*{*/ "m", &cookie )) == LBER_ERROR ) {
2429                         rs->sr_text = "Sync control : cookie decoding error";
2430                         return LDAP_PROTOCOL_ERROR;
2431                 }
2432         }
2433         if ( tag == LDAP_TAG_RELOAD_HINT ) {
2434                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
2435                         rs->sr_text = "Sync control : rhint decoding error";
2436                         return LDAP_PROTOCOL_ERROR;
2437                 }
2438         }
2439         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
2440                         rs->sr_text = "Sync control : decoding error";
2441                         return LDAP_PROTOCOL_ERROR;
2442         }
2443         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
2444         sr->sr_rhint = rhint;
2445         if (!BER_BVISNULL(&cookie)) {
2446                 ber_dupbv_x( &sr->sr_state.octet_str, &cookie, op->o_tmpmemctx );
2447                 slap_parse_sync_cookie( &sr->sr_state, op->o_tmpmemctx );
2448                 if ( sr->sr_state.rid == -1 ) {
2449                         rs->sr_text = "Sync control : cookie parsing error";
2450                         return LDAP_PROTOCOL_ERROR;
2451                 }
2452         }
2453
2454         op->o_controls[slap_cids.sc_LDAPsync] = sr;
2455
2456         op->o_sync = ctrl->ldctl_iscritical
2457                 ? SLAP_CONTROL_CRITICAL
2458                 : SLAP_CONTROL_NONCRITICAL;
2459
2460         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
2461
2462         return LDAP_SUCCESS;
2463 }
2464
2465 /* This overlay is set up for dynamic loading via moduleload. For static
2466  * configuration, you'll need to arrange for the slap_overinst to be
2467  * initialized and registered by some other function inside slapd.
2468  */
2469
2470 static slap_overinst            syncprov;
2471
2472 int
2473 syncprov_init()
2474 {
2475         int rc;
2476
2477         rc = register_supported_control( LDAP_CONTROL_SYNC,
2478                 SLAP_CTRL_HIDE|SLAP_CTRL_SEARCH, NULL,
2479                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
2480         if ( rc != LDAP_SUCCESS ) {
2481                 Debug( LDAP_DEBUG_ANY,
2482                         "syncprov_init: Failed to register control %d\n", rc, 0, 0 );
2483                 return rc;
2484         }
2485
2486         syncprov.on_bi.bi_type = "syncprov";
2487         syncprov.on_bi.bi_db_init = syncprov_db_init;
2488         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
2489         syncprov.on_bi.bi_db_open = syncprov_db_open;
2490         syncprov.on_bi.bi_db_close = syncprov_db_close;
2491
2492         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
2493         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
2494
2495         syncprov.on_bi.bi_op_add = syncprov_op_mod;
2496         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
2497         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
2498         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
2499         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
2500         syncprov.on_bi.bi_op_search = syncprov_op_search;
2501         syncprov.on_bi.bi_extended = syncprov_op_extended;
2502         syncprov.on_bi.bi_operational = syncprov_operational;
2503
2504         syncprov.on_bi.bi_cf_ocs = spocs;
2505
2506         rc = config_register_schema( spcfg, spocs );
2507         if ( rc ) return rc;
2508
2509         return overlay_register( &syncprov );
2510 }
2511
2512 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
2513 int
2514 init_module( int argc, char *argv[] )
2515 {
2516         return syncprov_init();
2517 }
2518 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
2519
2520 #endif /* defined(SLAPD_OVER_SYNCPROV) */