]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
Fix findpresent, include user's filter
[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 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
29 /* A modify request on a particular entry */
30 typedef struct modinst {
31         struct modinst *mi_next;
32         Operation *mi_op;
33 } modinst;
34
35 typedef struct modtarget {
36         struct modinst *mt_mods;
37         struct modinst *mt_tail;
38         Operation *mt_op;
39         ldap_pvt_thread_mutex_t mt_mutex;
40 } modtarget;
41
42 /* A queued result of a persistent search */
43 typedef struct syncres {
44         struct syncres *s_next;
45         struct berval s_dn;
46         struct berval s_ndn;
47         struct berval s_uuid;
48         struct berval s_csn;
49         char s_mode;
50         char s_isreference;
51 } syncres;
52
53 /* Record of a persistent search */
54 typedef struct syncops {
55         struct syncops *s_next;
56         struct berval   s_base;         /* ndn of search base */
57         ID              s_eid;          /* entryID of search base */
58         Operation       *s_op;          /* search op */
59         long    s_sid;
60         long    s_rid;
61         struct berval s_filterstr;
62         int             s_flags;        /* search status */
63         int             s_inuse;        /* reference count */
64         struct syncres *s_res;
65         struct syncres *s_restail;
66         ldap_pvt_thread_mutex_t s_mutex;
67 } syncops;
68
69 /* A received sync control */
70 typedef struct sync_control {
71         struct sync_cookie sr_state;
72         int sr_rhint;
73 } sync_control;
74
75 #if 0 /* moved back to slap.h */
76 #define o_sync  o_ctrlflag[slap_cids.sc_LDAPsync]
77 #endif
78 /* o_sync_mode uses data bits of o_sync */
79 #define o_sync_mode     o_ctrlflag[slap_cids.sc_LDAPsync]
80
81 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
82 #define SLAP_SYNC_REFRESH                               (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
83 #define SLAP_SYNC_PERSIST                               (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
84 #define SLAP_SYNC_REFRESH_AND_PERSIST   (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
85
86 #define PS_IS_REFRESHING        0x01
87
88 /* Record of which searches matched at premodify step */
89 typedef struct syncmatches {
90         struct syncmatches *sm_next;
91         syncops *sm_op;
92 } syncmatches;
93
94 /* The main state for this overlay */
95 typedef struct syncprov_info_t {
96         syncops         *si_ops;
97         struct berval   si_ctxcsn;      /* ldapsync context */
98         int             si_chkops;      /* checkpointing info */
99         int             si_chktime;
100         int             si_numops;      /* number of ops since last checkpoint */
101         time_t  si_chklast;     /* time of last checkpoint */
102         Avlnode *si_mods;       /* entries being modified */
103         ldap_pvt_thread_mutex_t si_csn_mutex;
104         ldap_pvt_thread_mutex_t si_ops_mutex;
105         ldap_pvt_thread_mutex_t si_mods_mutex;
106         char            si_ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
107 } syncprov_info_t;
108
109 typedef struct opcookie {
110         slap_overinst *son;
111         syncmatches *smatches;
112         struct berval sdn;      /* DN of entry, for deletes */
113         struct berval sndn;
114         struct berval suuid;    /* UUID of entry */
115         struct berval sctxcsn;
116         int sreference; /* Is the entry a reference? */
117 } opcookie;
118
119 typedef struct fbase_cookie {
120         struct berval *fdn;     /* DN of a modified entry, for scope testing */
121         syncops *fss;   /* persistent search we're testing against */
122         int fbase;      /* if TRUE we found the search base and it's still valid */
123         int fscope;     /* if TRUE then fdn is within the psearch scope */
124 } fbase_cookie;
125
126 static AttributeName csn_anlist[2];
127 static AttributeName uuid_anlist[2];
128
129 /* Build a LDAPsync intermediate state control */
130 static int
131 syncprov_state_ctrl(
132         Operation       *op,
133         SlapReply       *rs,
134         Entry           *e,
135         int             entry_sync_state,
136         LDAPControl     **ctrls,
137         int             num_ctrls,
138         int             send_cookie,
139         struct berval   *cookie )
140 {
141         Attribute* a;
142         int ret;
143         int res;
144         const char *text = NULL;
145
146         BerElementBuffer berbuf;
147         BerElement *ber = (BerElement *)&berbuf;
148
149         struct berval   entryuuid_bv = BER_BVNULL;
150
151         ber_init2( ber, 0, LBER_USE_DER );
152         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
153
154         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
155
156         for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
157                 AttributeDescription *desc = a->a_desc;
158                 if ( desc == slap_schema.si_ad_entryUUID ) {
159                         entryuuid_bv = a->a_nvals[0];
160                         break;
161                 }
162         }
163
164         if ( send_cookie && cookie ) {
165                 ber_printf( ber, "{eOON}",
166                         entry_sync_state, &entryuuid_bv, cookie );
167         } else {
168                 ber_printf( ber, "{eON}",
169                         entry_sync_state, &entryuuid_bv );
170         }
171
172         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
173         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
174         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
175
176         ber_free_buf( ber );
177
178         if ( ret < 0 ) {
179                 Debug( LDAP_DEBUG_TRACE,
180                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
181                         0, 0, 0 );
182                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
183                 return ret;
184         }
185
186         return LDAP_SUCCESS;
187 }
188
189 /* Build a LDAPsync final state control */
190 static int
191 syncprov_done_ctrl(
192         Operation       *op,
193         SlapReply       *rs,
194         LDAPControl     **ctrls,
195         int                     num_ctrls,
196         int                     send_cookie,
197         struct berval *cookie,
198         int                     refreshDeletes )
199 {
200         int ret;
201         BerElementBuffer berbuf;
202         BerElement *ber = (BerElement *)&berbuf;
203
204         ber_init2( ber, NULL, LBER_USE_DER );
205         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
206
207         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
208
209         ber_printf( ber, "{" );
210         if ( send_cookie && cookie ) {
211                 ber_printf( ber, "O", cookie );
212         }
213         if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
214                 ber_printf( ber, "b", refreshDeletes );
215         }
216         ber_printf( ber, "N}" );
217
218         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
219         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
220         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
221
222         ber_free_buf( ber );
223
224         if ( ret < 0 ) {
225                 Debug( LDAP_DEBUG_TRACE,
226                         "syncprov_done_ctrl: ber_flatten2 failed\n",
227                         0, 0, 0 );
228                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
229                 return ret;
230         }
231
232         return LDAP_SUCCESS;
233 }
234
235 #if 0
236 /* Generate state based on session log - not implemented yet */
237 static int
238 syncprov_state_ctrl_from_slog(
239         Operation       *op,
240         SlapReply       *rs,
241         struct slog_entry *slog_e,
242         int                     entry_sync_state,
243         LDAPControl     **ctrls,
244         int                     num_ctrls,
245         int                     send_cookie,
246         struct berval   *cookie)
247 {
248         Attribute* a;
249         int ret;
250         int res;
251         const char *text = NULL;
252
253         BerElementBuffer berbuf;
254         BerElement *ber = (BerElement *)&berbuf;
255
256         struct berval entryuuid_bv      = BER_BVNULL;
257
258         ber_init2( ber, NULL, LBER_USE_DER );
259         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
260
261         ctrls[num_ctrls] = ch_malloc ( sizeof ( LDAPControl ) );
262
263         entryuuid_bv = slog_e->sl_uuid;
264
265         if ( send_cookie && cookie ) {
266                 ber_printf( ber, "{eOON}",
267                         entry_sync_state, &entryuuid_bv, cookie );
268         } else {
269                 ber_printf( ber, "{eON}",
270                         entry_sync_state, &entryuuid_bv );
271         }
272
273         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
274         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
275         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
276
277         ber_free_buf( ber );
278
279         if ( ret < 0 ) {
280                 Debug( LDAP_DEBUG_TRACE,
281                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
282                         0, 0, 0 );
283                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
284                 return ret;
285         }
286
287         return LDAP_SUCCESS;
288 }
289 #endif
290
291 static int
292 syncprov_sendinfo(
293         Operation       *op,
294         SlapReply       *rs,
295         int                     type,
296         struct berval *cookie,
297         int                     refreshDone,
298         BerVarray       syncUUIDs,
299         int                     refreshDeletes )
300 {
301         BerElementBuffer berbuf;
302         BerElement *ber = (BerElement *)&berbuf;
303         struct berval rspdata;
304
305         int ret;
306
307         ber_init2( ber, NULL, LBER_USE_DER );
308         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
309
310         if ( type ) {
311                 switch ( type ) {
312                 case LDAP_TAG_SYNC_NEW_COOKIE:
313                         ber_printf( ber, "tO", type, cookie );
314                         break;
315                 case LDAP_TAG_SYNC_REFRESH_DELETE:
316                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
317                         ber_printf( ber, "t{", type );
318                         if ( cookie ) {
319                                 ber_printf( ber, "O", cookie );
320                         }
321                         if ( refreshDone == 0 ) {
322                                 ber_printf( ber, "b", refreshDone );
323                         }
324                         ber_printf( ber, "N}" );
325                         break;
326                 case LDAP_TAG_SYNC_ID_SET:
327                         ber_printf( ber, "t{", type );
328                         if ( cookie ) {
329                                 ber_printf( ber, "O", cookie );
330                         }
331                         if ( refreshDeletes == 1 ) {
332                                 ber_printf( ber, "b", refreshDeletes );
333                         }
334                         ber_printf( ber, "[W]", syncUUIDs );
335                         ber_printf( ber, "N}" );
336                         break;
337                 default:
338                         Debug( LDAP_DEBUG_TRACE,
339                                 "syncprov_sendinfo: invalid syncinfo type (%d)\n",
340                                 type, 0, 0 );
341                         return LDAP_OTHER;
342                 }
343         }
344
345         ret = ber_flatten2( ber, &rspdata, 0 );
346
347         if ( ret < 0 ) {
348                 Debug( LDAP_DEBUG_TRACE,
349                         "syncprov_sendinfo: ber_flatten2 failed\n",
350                         0, 0, 0 );
351                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
352                 return ret;
353         }
354
355         rs->sr_rspoid = LDAP_SYNC_INFO;
356         rs->sr_rspdata = &rspdata;
357         send_ldap_intermediate( op, rs );
358         rs->sr_rspdata = NULL;
359         ber_free_buf( ber );
360
361         return LDAP_SUCCESS;
362 }
363
364 /* Find a modtarget in an AVL tree */
365 static int
366 sp_avl_cmp( const void *c1, const void *c2 )
367 {
368         const modtarget *m1, *m2;
369         int rc;
370
371         m1 = c1; m2 = c2;
372         rc = m1->mt_op->o_req_ndn.bv_len - m2->mt_op->o_req_ndn.bv_len;
373
374         if ( rc ) return rc;
375         return ber_bvcmp( &m1->mt_op->o_req_ndn, &m2->mt_op->o_req_ndn );
376 }
377
378 /* syncprov_findbase:
379  *   finds the true DN of the base of a search (with alias dereferencing) and
380  * checks to make sure the base entry doesn't get replaced with a different
381  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
382  * change is detected, any persistent search on this base must be terminated /
383  * reloaded.
384  *   On the first call, we just save the DN and entryID. On subsequent calls
385  * we compare the DN and entryID with the saved values.
386  */
387 static int
388 findbase_cb( Operation *op, SlapReply *rs )
389 {
390         slap_callback *sc = op->o_callback;
391
392         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
393                 fbase_cookie *fc = sc->sc_private;
394
395                 /* If no entryID, we're looking for the first time.
396                  * Just store whatever we got.
397                  */
398                 if ( fc->fss->s_eid == NOID ) {
399                         fc->fbase = 1;
400                         fc->fss->s_eid = rs->sr_entry->e_id;
401                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
402
403                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
404                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
405
406                 /* OK, the DN is the same and the entryID is the same. Now
407                  * see if the fdn resides in the scope.
408                  */
409                         fc->fbase = 1;
410                         switch ( fc->fss->s_op->ors_scope ) {
411                         case LDAP_SCOPE_BASE:
412                                 fc->fscope = dn_match( fc->fdn, &rs->sr_entry->e_nname );
413                                 break;
414                         case LDAP_SCOPE_ONELEVEL: {
415                                 struct berval pdn;
416                                 dnParent( fc->fdn, &pdn );
417                                 fc->fscope = dn_match( &pdn, &rs->sr_entry->e_nname );
418                                 break; }
419                         case LDAP_SCOPE_SUBTREE:
420                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname );
421                                 break;
422 #ifdef LDAP_SCOPE_SUBORDINATE
423                         case LDAP_SCOPE_SUBORDINATE:
424                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname ) &&
425                                         !dn_match( fc->fdn, &rs->sr_entry->e_nname );
426                                 break;
427 #endif
428                         }
429                 }
430         }
431         if ( rs->sr_err != LDAP_SUCCESS ) {
432                 Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err,0,0 );
433         }
434         return LDAP_SUCCESS;
435 }
436
437 static int
438 syncprov_findbase( Operation *op, fbase_cookie *fc )
439 {
440         opcookie *opc = op->o_callback->sc_private;
441         slap_overinst *on = opc->son;
442         syncprov_info_t         *si = on->on_bi.bi_private;
443
444         slap_callback cb = {0};
445         Operation fop;
446         SlapReply frs = { REP_RESULT };
447         int rc;
448
449         fop = *op;
450
451         cb.sc_response = findbase_cb;
452         cb.sc_private = fc;
453
454         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync mode */
455         fop.o_callback = &cb;
456         fop.o_tag = LDAP_REQ_SEARCH;
457         fop.ors_scope = LDAP_SCOPE_BASE;
458         fop.ors_deref = fc->fss->s_op->ors_deref;
459         fop.ors_limit = NULL;
460         fop.ors_slimit = 1;
461         fop.ors_tlimit = SLAP_NO_LIMIT;
462         fop.ors_attrs = slap_anlist_no_attrs;
463         fop.ors_attrsonly = 1;
464         fop.ors_filter = fc->fss->s_op->ors_filter;
465         fop.ors_filterstr = fc->fss->s_op->ors_filterstr;
466
467         fop.o_req_ndn = fc->fss->s_op->o_req_ndn;
468
469         fop.o_bd->bd_info = on->on_info->oi_orig;
470         rc = fop.o_bd->be_search( &fop, &frs );
471         fop.o_bd->bd_info = (BackendInfo *)on;
472
473         if ( fc->fbase ) return LDAP_SUCCESS;
474
475         /* If entryID has changed, then the base of this search has
476          * changed. Invalidate the psearch.
477          */
478         return LDAP_NO_SUCH_OBJECT;
479 }
480
481 /* syncprov_findcsn:
482  *   This function has three different purposes, but they all use a search
483  * that filters on entryCSN so they're combined here.
484  * 1: at startup time, after a contextCSN has been read from the database,
485  * we search for all entries with CSN >= contextCSN in case the contextCSN
486  * was not checkpointed at the previous shutdown.
487  *
488  * 2: when the current contextCSN is known and we have a sync cookie, we search
489  * for one entry with CSN <= the cookie CSN. (Used to search for =.) If an
490  * entry is found, the cookie CSN is valid, otherwise it is stale.
491  *
492  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
493  * CSN, and generate Present records for them. We always collect this result
494  * in SyncID sets, even if there's only one match.
495  */
496 #define FIND_MAXCSN     1
497 #define FIND_CSN        2
498 #define FIND_PRESENT    3
499
500 static int
501 findmax_cb( Operation *op, SlapReply *rs )
502 {
503         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
504                 struct berval *maxcsn = op->o_callback->sc_private;
505                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
506                         slap_schema.si_ad_entryCSN );
507
508                 if ( a && ber_bvcmp( &a->a_vals[0], maxcsn )) {
509                         maxcsn->bv_len = a->a_vals[0].bv_len;
510                         strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
511                 }
512         }
513         return LDAP_SUCCESS;
514 }
515
516 static int
517 findcsn_cb( Operation *op, SlapReply *rs )
518 {
519         slap_callback *sc = op->o_callback;
520
521         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
522                 sc->sc_private = (void *)1;
523         }
524         return LDAP_SUCCESS;
525 }
526
527 /* Build a list of entryUUIDs for sending in a SyncID set */
528
529 #define UUID_LEN        16
530
531 typedef struct fpres_cookie {
532         int num;
533         BerVarray uuids;
534         char *last;
535 } fpres_cookie;
536
537 static int
538 findpres_cb( Operation *op, SlapReply *rs )
539 {
540         slap_callback *sc = op->o_callback;
541         fpres_cookie *pc = sc->sc_private;
542         int ret = SLAP_CB_CONTINUE;
543
544         if ( rs->sr_type == REP_SEARCH ) {
545                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
546                         slap_schema.si_ad_entryUUID );
547                 if ( a ) {
548                         pc->uuids[pc->num].bv_val = pc->last;
549                         AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
550                                 pc->uuids[pc->num].bv_len );
551                         pc->num++;
552                         pc->last = pc->uuids[pc->num].bv_val;
553                         pc->uuids[pc->num].bv_val = NULL;
554                 }
555                 ret = LDAP_SUCCESS;
556                 if ( pc->num == SLAP_SYNCUUID_SET_SIZE ) {
557                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
558                                 0, pc->uuids, 0 );
559                         pc->uuids[pc->num].bv_val = pc->last;
560                         pc->num = 0;
561                         pc->last = pc->uuids[0].bv_val;
562                 }
563
564         } else if ( rs->sr_type == REP_RESULT ) {
565                 ret = rs->sr_err;
566                 if ( pc->num ) {
567                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
568                                 0, pc->uuids, 0 );
569                         pc->uuids[pc->num].bv_val = pc->last;
570                         pc->num = 0;
571                         pc->last = pc->uuids[0].bv_val;
572                 }
573         }
574         return ret;
575 }
576
577 static int
578 syncprov_findcsn( Operation *op, int mode )
579 {
580         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
581         syncprov_info_t         *si = on->on_bi.bi_private;
582
583         slap_callback cb = {0};
584         Operation fop;
585         SlapReply frs = { REP_RESULT };
586         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
587         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
588         struct berval fbuf, maxcsn;
589         Filter cf, af;
590         AttributeAssertion eq;
591         int i, rc = LDAP_SUCCESS;
592         fpres_cookie pcookie;
593         sync_control *srs;
594
595         if ( mode != FIND_MAXCSN ) {
596                 srs = op->o_controls[slap_cids.sc_LDAPsync];
597
598                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
599                         return LDAP_OTHER;
600                 }
601         }
602
603         fop = *op;
604         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
605
606         fbuf.bv_val = buf;
607         cf.f_ava = &eq;
608         cf.f_av_desc = slap_schema.si_ad_entryCSN;
609         cf.f_next = NULL;
610
611         fop.o_callback = &cb;
612         fop.ors_limit = NULL;
613         fop.ors_tlimit = SLAP_NO_LIMIT;
614         fop.ors_filter = &cf;
615         fop.ors_filterstr = fbuf;
616
617         switch( mode ) {
618         case FIND_MAXCSN:
619                 cf.f_choice = LDAP_FILTER_GE;
620                 cf.f_av_value = si->si_ctxcsn;
621                 fbuf.bv_len = sprintf( buf, "(entryCSN>=%s)",
622                         cf.f_av_value.bv_val );
623                 fop.ors_attrsonly = 0;
624                 fop.ors_attrs = csn_anlist;
625                 fop.ors_slimit = SLAP_NO_LIMIT;
626                 cb.sc_private = &maxcsn;
627                 cb.sc_response = findmax_cb;
628                 maxcsn.bv_val = cbuf;
629                 maxcsn.bv_len = 0;
630                 break;
631         case FIND_CSN:
632                 cf.f_choice = LDAP_FILTER_LE;
633                 cf.f_av_value = *srs->sr_state.ctxcsn;
634                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)",
635                         cf.f_av_value.bv_val );
636                 fop.ors_attrsonly = 1;
637                 fop.ors_attrs = slap_anlist_no_attrs;
638                 fop.ors_slimit = 1;
639                 cb.sc_private = NULL;
640                 cb.sc_response = findcsn_cb;
641                 break;
642         case FIND_PRESENT:
643                 af.f_choice = LDAP_FILTER_AND;
644                 af.f_next = NULL;
645                 af.f_and = &cf;
646                 cf.f_choice = LDAP_FILTER_LE;
647                 cf.f_av_value = *srs->sr_state.ctxcsn;
648                 cf.f_next = op->ors_filter;
649                 fop.ors_filter = &af;
650                 filter2bv_x( &fop, fop.ors_filter, &fop.ors_filterstr );
651                 fop.ors_attrsonly = 0;
652                 fop.ors_attrs = uuid_anlist;
653                 fop.ors_slimit = SLAP_NO_LIMIT;
654                 /* We want pure entries, not referrals */
655                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
656                 cb.sc_private = &pcookie;
657                 cb.sc_response = findpres_cb;
658                 pcookie.num = 0;
659
660                 /* preallocate storage for a full set */
661                 pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
662                         sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
663                         op->o_tmpmemctx );
664                 pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
665                 pcookie.uuids[0].bv_val = pcookie.last;
666                 pcookie.uuids[0].bv_len = UUID_LEN;
667                 for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
668                         pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
669                         pcookie.uuids[i].bv_len = UUID_LEN;
670                 }
671                 break;
672         }
673
674         fop.o_bd->bd_info = on->on_info->oi_orig;
675         fop.o_bd->be_search( &fop, &frs );
676         fop.o_bd->bd_info = (BackendInfo *)on;
677
678         switch( mode ) {
679         case FIND_MAXCSN:
680                 if ( maxcsn.bv_len ) {
681                         strcpy( si->si_ctxcsnbuf, maxcsn.bv_val );
682                         si->si_ctxcsn.bv_len = maxcsn.bv_len;
683                 }
684                 break;
685         case FIND_CSN:
686                 /* If matching CSN was not found, invalidate the context. */
687                 if ( !cb.sc_private ) rc = LDAP_NO_SUCH_OBJECT;
688                 break;
689         case FIND_PRESENT:
690                 op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
691                 op->o_tmpfree( fop.ors_filterstr.bv_val, op->o_tmpmemctx );
692                 break;
693         }
694
695         return rc;
696 }
697
698 /* Queue a persistent search response if still in Refresh stage */
699 static int
700 syncprov_qresp( opcookie *opc, syncops *so, int mode )
701 {
702         syncres *sr;
703
704         sr = ch_malloc(sizeof(syncres) + opc->suuid.bv_len + 1 +
705                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1 + opc->sctxcsn.bv_len + 1 );
706         sr->s_next = NULL;
707         sr->s_dn.bv_val = (char *)(sr + 1);
708         sr->s_mode = mode;
709         sr->s_isreference = opc->sreference;
710         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val, opc->sdn.bv_val );
711         *(sr->s_ndn.bv_val++) = '\0';
712         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val, opc->sndn.bv_val );
713         *(sr->s_uuid.bv_val++) = '\0';
714         sr->s_csn.bv_val = lutil_strcopy( sr->s_uuid.bv_val, opc->suuid.bv_val );
715
716         if ( !so->s_res ) {
717                 so->s_res = sr;
718         } else {
719                 so->s_restail->s_next = sr;
720         }
721         so->s_restail = sr;
722         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
723         return LDAP_SUCCESS;
724 }
725
726 /* Send a persistent search response */
727 static int
728 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, Entry *e, int mode, int queue )
729 {
730         slap_overinst *on = opc->son;
731         syncprov_info_t *si = on->on_bi.bi_private;
732
733         SlapReply rs = { REP_SEARCH };
734         LDAPControl *ctrls[2];
735         struct berval cookie;
736         Entry e_uuid = {0};
737         Attribute a_uuid = {0};
738         Operation sop = *so->s_op;
739         Opheader ohdr;
740
741         ohdr = *sop.o_hdr;
742         sop.o_hdr = &ohdr;
743         sop.o_tmpmemctx = op->o_tmpmemctx;
744         sop.o_bd = op->o_bd;
745         sop.o_controls = op->o_controls;
746
747         if ( queue && (so->s_flags & PS_IS_REFRESHING) ) {
748                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
749                 if ( so->s_flags & PS_IS_REFRESHING )
750                         return syncprov_qresp( opc, so, mode );
751                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
752         }
753
754         ctrls[1] = NULL;
755         slap_compose_sync_cookie( op, &cookie, &opc->sctxcsn,
756                 so->s_sid, so->s_rid );
757
758         e_uuid.e_attrs = &a_uuid;
759         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
760         a_uuid.a_nvals = &opc->suuid;
761         rs.sr_err = syncprov_state_ctrl( &sop, &rs, &e_uuid,
762                 mode, ctrls, 0, 1, &cookie );
763
764         rs.sr_entry = e;
765         rs.sr_ctrls = ctrls;
766         switch( mode ) {
767         case LDAP_SYNC_ADD:
768                 if ( opc->sreference ) {
769                         rs.sr_ref = get_entry_referrals( &sop, e );
770                         send_search_reference( &sop, &rs );
771                         ber_bvarray_free( rs.sr_ref );
772                         break;
773                 }
774                 /* fallthru */
775         case LDAP_SYNC_MODIFY:
776                 rs.sr_attrs = sop.ors_attrs;
777                 send_search_entry( &sop, &rs );
778                 break;
779         case LDAP_SYNC_DELETE:
780                 e_uuid.e_attrs = NULL;
781                 e_uuid.e_name = opc->sdn;
782                 e_uuid.e_nname = opc->sndn;
783                 rs.sr_entry = &e_uuid;
784                 if ( opc->sreference ) {
785                         struct berval bv = BER_BVNULL;
786                         rs.sr_ref = &bv;
787                         send_search_reference( &sop, &rs );
788                 } else {
789                         send_search_entry( &sop, &rs );
790                 }
791                 break;
792         default:
793                 assert(0);
794         }
795         op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
796         rs.sr_ctrls = NULL;
797         return rs.sr_err;
798 }
799
800 static void
801 syncprov_free_syncop( syncops *so )
802 {
803         syncres *sr, *srnext;
804
805         ldap_pvt_thread_mutex_lock( &so->s_mutex );
806         so->s_inuse--;
807         if ( so->s_inuse > 0 ) {
808                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
809                 return;
810         }
811         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
812         filter_free( so->s_op->ors_filter );
813         ch_free( so->s_op );
814         ch_free( so->s_base.bv_val );
815         for ( sr=so->s_res; sr; sr=srnext ) {
816                 srnext = sr->s_next;
817                 ch_free( sr );
818         }
819         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
820         ch_free( so );
821 }
822
823 static int
824 syncprov_drop_psearch( syncops *so )
825 {
826         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
827         so->s_op->o_conn->c_n_ops_executing--;
828         so->s_op->o_conn->c_n_ops_completed++;
829         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
830         syncprov_free_syncop( so );
831 }
832
833 static int
834 syncprov_op_abandon( Operation *op, SlapReply *rs )
835 {
836         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
837         syncprov_info_t         *si = on->on_bi.bi_private;
838         syncops *so, *soprev;
839
840         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
841         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
842                 soprev=so, so=so->s_next ) {
843                 if ( so->s_op->o_connid == op->o_connid &&
844                         so->s_op->o_msgid == op->orn_msgid ) {
845                                 so->s_op->o_abandon = 1;
846                                 soprev->s_next = so->s_next;
847                                 break;
848                 }
849         }
850         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
851         if ( so ) {
852                 /* Is this really a Cancel exop? */
853                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
854                         rs->sr_err = LDAP_CANCELLED;
855                         send_ldap_result( so->s_op, rs );
856                 }
857                 syncprov_drop_psearch( so );
858         }
859         return SLAP_CB_CONTINUE;
860 }
861
862 /* Find which persistent searches are affected by this operation */
863 static void
864 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
865 {
866         slap_overinst *on = opc->son;
867         syncprov_info_t         *si = on->on_bi.bi_private;
868
869         fbase_cookie fc;
870         syncops *ss, *sprev, *snext;
871         Entry *e;
872         Attribute *a;
873         int rc;
874         struct berval newdn;
875         int freefdn = 0;
876
877         fc.fdn = &op->o_req_ndn;
878         /* compute new DN */
879         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
880                 struct berval pdn;
881                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
882                 else dnParent( fc.fdn, &pdn );
883                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
884                 fc.fdn = &newdn;
885                 freefdn = 1;
886         }
887         if ( op->o_tag != LDAP_REQ_ADD ) {
888                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
889                 rc = be_entry_get_rw( op, fc.fdn, NULL, NULL, 0, &e );
890                 op->o_bd->bd_info = (BackendInfo *)on;
891                 if ( rc ) return;
892         } else {
893                 e = op->ora_e;
894         }
895
896         /* Never replicate these */
897         if ( is_entry_syncConsumerSubentry( e )) {
898                 goto done;
899         }
900         if ( saveit ) {
901                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
902                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
903                 opc->sreference = is_entry_referral( e );
904         }
905         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
906                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
907                 if ( a )
908                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
909         }
910
911         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
912         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
913                 sprev = ss, ss=snext)
914         {
915                 syncmatches *sm;
916                 int found = 0;
917
918                 snext = ss->s_next;
919                 /* validate base */
920                 fc.fss = ss;
921                 fc.fbase = 0;
922                 fc.fscope = 0;
923
924                 /* If the base of the search is missing, signal a refresh */
925                 rc = syncprov_findbase( op, &fc );
926                 if ( rc != LDAP_SUCCESS ) {
927                         SlapReply rs = {REP_RESULT};
928                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
929                                 "search base has changed" );
930                         sprev->s_next = snext;
931                         syncprov_drop_psearch( ss );
932                         continue;
933                 }
934
935                 /* If we're sending results now, look for this op in old matches */
936                 if ( !saveit ) {
937                         syncmatches *old;
938                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
939                                 old=sm, sm=sm->sm_next ) {
940                                 if ( sm->sm_op == ss ) {
941                                         found = 1;
942                                         old->sm_next = sm->sm_next;
943                                         op->o_tmpfree( sm, op->o_tmpmemctx );
944                                         break;
945                                 }
946                         }
947                 }
948
949                 /* check if current o_req_dn is in scope and matches filter */
950                 if ( fc.fscope && test_filter( op, e, ss->s_op->ors_filter ) ==
951                         LDAP_COMPARE_TRUE ) {
952                         if ( saveit ) {
953                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
954                                 sm->sm_next = opc->smatches;
955                                 sm->sm_op = ss;
956                                 ss->s_inuse++;
957                                 opc->smatches = sm;
958                         } else {
959                                 /* if found send UPDATE else send ADD */
960                                 syncprov_sendresp( op, opc, ss, e,
961                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD, 1 );
962                         }
963                 } else if ( !saveit && found ) {
964                         /* send DELETE */
965                         syncprov_sendresp( op, opc, ss, NULL, LDAP_SYNC_DELETE, 1 );
966                 }
967         }
968         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
969 done:
970         if ( op->o_tag != LDAP_REQ_ADD ) {
971                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
972                 be_entry_release_r( op, e );
973                 op->o_bd->bd_info = (BackendInfo *)on;
974         }
975         if ( freefdn ) {
976                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
977         }
978 }
979
980 static int
981 syncprov_op_cleanup( Operation *op, SlapReply *rs )
982 {
983         slap_callback *cb = op->o_callback;
984         opcookie *opc = cb->sc_private;
985         slap_overinst *on = opc->son;
986         syncprov_info_t         *si = on->on_bi.bi_private;
987         syncmatches *sm, *snext;
988         modtarget *mt, mtdummy;
989
990         for (sm = opc->smatches; sm; sm=snext) {
991                 snext = sm->sm_next;
992                 syncprov_free_syncop( sm->sm_op );
993                 op->o_tmpfree( sm, op->o_tmpmemctx );
994         }
995
996         /* Remove op from lock table */
997         mtdummy.mt_op = op;
998         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
999         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1000         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1001         if ( mt ) {
1002                 modinst *mi = mt->mt_mods;
1003
1004                 /* If there are more, promote the next one */
1005                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1006                 if ( mi->mi_next ) {
1007                         mt->mt_mods = mi->mi_next;
1008                         mt->mt_op = mt->mt_mods->mi_op;
1009                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1010                 } else {
1011                         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1012                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
1013                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1014                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1015                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1016                         ch_free( mt );
1017                 }
1018         }
1019         if ( !BER_BVISNULL( &opc->suuid ))
1020                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1021         if ( !BER_BVISNULL( &opc->sndn ))
1022                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1023         if ( !BER_BVISNULL( &opc->sdn ))
1024                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1025         op->o_callback = cb->sc_next;
1026         op->o_tmpfree(cb, op->o_tmpmemctx);
1027 }
1028
1029 static void
1030 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1031 {
1032         syncprov_info_t         *si = on->on_bi.bi_private;
1033         Modifications mod;
1034         Operation opm;
1035         struct berval bv[2];
1036         BackendInfo *orig;
1037         slap_callback cb = {0};
1038
1039         mod.sml_values = bv;
1040         bv[1].bv_val = NULL;
1041         bv[0] = si->si_ctxcsn;
1042         mod.sml_nvalues = NULL;
1043         mod.sml_desc = slap_schema.si_ad_contextCSN;
1044         mod.sml_op = LDAP_MOD_REPLACE;
1045         mod.sml_next = NULL;
1046
1047         cb.sc_response = slap_null_cb;
1048         opm = *op;
1049         opm.o_tag = LDAP_REQ_MODIFY;
1050         opm.o_callback = &cb;
1051         opm.orm_modlist = &mod;
1052         opm.o_req_dn = op->o_bd->be_suffix[0];
1053         opm.o_req_ndn = op->o_bd->be_nsuffix[0];
1054         orig = opm.o_bd->bd_info;
1055         opm.o_bd->bd_info = on->on_info->oi_orig;
1056         opm.o_bd->be_modify( &opm, rs );
1057 }
1058
1059 static int
1060 syncprov_op_response( Operation *op, SlapReply *rs )
1061 {
1062         opcookie *opc = op->o_callback->sc_private;
1063         slap_overinst *on = opc->son;
1064         syncprov_info_t         *si = on->on_bi.bi_private;
1065         syncmatches *sm;
1066
1067         if ( rs->sr_err == LDAP_SUCCESS )
1068         {
1069                 struct berval maxcsn;
1070                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1071
1072                 /* Update our context CSN */
1073                 cbuf[0] = '\0';
1074                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1075                 slap_get_commit_csn( op, &maxcsn );
1076                 if ( !BER_BVISNULL( &maxcsn ) ) {
1077                         strcpy( cbuf, maxcsn.bv_val );
1078                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn ) > 0 ) {
1079                                 strcpy( si->si_ctxcsnbuf, cbuf );
1080                                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
1081                         }
1082                 }
1083
1084                 si->si_numops++;
1085                 if ( si->si_chkops || si->si_chktime ) {
1086                         int do_check=0;
1087                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1088                                 do_check = 1;
1089                                 si->si_numops = 0;
1090                         }
1091                         if ( si->si_chktime &&
1092                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1093                                 do_check = 1;
1094                                 si->si_chklast = op->o_time;
1095                         }
1096                         if ( do_check ) {
1097                                 syncprov_checkpoint( op, rs, on );
1098                         }
1099                 }
1100                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1101
1102                 opc->sctxcsn.bv_len = maxcsn.bv_len;
1103                 opc->sctxcsn.bv_val = cbuf;
1104
1105                 /* Handle any persistent searches */
1106                 if ( si->si_ops ) {
1107                         switch(op->o_tag) {
1108                         case LDAP_REQ_ADD:
1109                         case LDAP_REQ_MODIFY:
1110                         case LDAP_REQ_MODRDN:
1111                         case LDAP_REQ_EXTENDED:
1112                                 syncprov_matchops( op, opc, 0 );
1113                                 break;
1114                         case LDAP_REQ_DELETE:
1115                                 /* for each match in opc->smatches:
1116                                  *   send DELETE msg
1117                                  */
1118                                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1119                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1120                                         if ( sm->sm_op->s_op->o_abandon )
1121                                                 continue;
1122                                         syncprov_sendresp( op, opc, sm->sm_op, NULL,
1123                                                 LDAP_SYNC_DELETE, 1 );
1124                                 }
1125                                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1126                                 break;
1127                         }
1128                 }
1129
1130         }
1131         return SLAP_CB_CONTINUE;
1132 }
1133
1134 /* We don't use a subentry to store the context CSN any more.
1135  * We expose the current context CSN as an operational attribute
1136  * of the suffix entry.
1137  */
1138 static int
1139 syncprov_op_compare( Operation *op, SlapReply *rs )
1140 {
1141         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1142         syncprov_info_t         *si = on->on_bi.bi_private;
1143         int rc = SLAP_CB_CONTINUE;
1144
1145         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1146                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1147         {
1148                 Entry e = {0};
1149                 Attribute a = {0};
1150                 struct berval bv[2];
1151
1152                 e.e_name = op->o_bd->be_suffix[0];
1153                 e.e_nname = op->o_bd->be_nsuffix[0];
1154
1155                 BER_BVZERO( &bv[1] );
1156                 bv[0] = si->si_ctxcsn;
1157
1158                 a.a_desc = slap_schema.si_ad_contextCSN;
1159                 a.a_vals = bv;
1160                 a.a_nvals = a.a_vals;
1161
1162                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1163
1164                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1165                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1166                 if ( ! rs->sr_err ) {
1167                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1168                         goto return_results;
1169                 }
1170
1171                 if ( get_assert( op ) &&
1172                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1173                 {
1174                         rs->sr_err = LDAP_ASSERTION_FAILED;
1175                         goto return_results;
1176                 }
1177
1178
1179                 rs->sr_err = LDAP_COMPARE_FALSE;
1180
1181                 if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
1182                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1183                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1184                                 a.a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
1185                 {
1186                         rs->sr_err = LDAP_COMPARE_TRUE;
1187                 }
1188
1189 return_results:;
1190
1191                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1192
1193                 send_ldap_result( op, rs );
1194
1195                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1196                         rs->sr_err = LDAP_SUCCESS;
1197                 }
1198                 rc = rs->sr_err;
1199         }
1200
1201         return rc;
1202 }
1203
1204 static int
1205 syncprov_op_mod( Operation *op, SlapReply *rs )
1206 {
1207         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1208         syncprov_info_t         *si = on->on_bi.bi_private;
1209
1210         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+
1211                 sizeof(opcookie) +
1212                 (si->si_ops ? sizeof(modinst) : 0 ),
1213                 op->o_tmpmemctx);
1214         opcookie *opc = (opcookie *)(cb+1);
1215         opc->son = on;
1216         cb->sc_response = syncprov_op_response;
1217         cb->sc_cleanup = syncprov_op_cleanup;
1218         cb->sc_private = opc;
1219         cb->sc_next = op->o_callback;
1220         op->o_callback = cb;
1221
1222         /* If there are active persistent searches, lock this operation.
1223          * See seqmod.c for the locking logic on its own.
1224          */
1225         if ( si->si_ops ) {
1226                 modtarget *mt, mtdummy;
1227                 modinst *mi;
1228
1229                 mi = (modinst *)(opc+1);
1230                 mi->mi_op = op;
1231
1232                 /* See if we're already modifying this entry... */
1233                 mtdummy.mt_op = op;
1234                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1235                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1236                 if ( mt ) {
1237                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1238                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1239                         mt->mt_tail->mi_next = mi;
1240                         mt->mt_tail = mi;
1241                         /* wait for this op to get to head of list */
1242                         while ( mt->mt_mods != mi ) {
1243                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1244                                 ldap_pvt_thread_yield();
1245                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1246                         }
1247                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1248                 } else {
1249                         /* Record that we're modifying this entry now */
1250                         mt = ch_malloc( sizeof(modtarget) );
1251                         mt->mt_mods = mi;
1252                         mt->mt_tail = mi;
1253                         mt->mt_op = mi->mi_op;
1254                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1255                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1256                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1257                 }
1258
1259                 if ( op->o_tag != LDAP_REQ_ADD )
1260                         syncprov_matchops( op, opc, 1 );
1261         }
1262
1263         return SLAP_CB_CONTINUE;
1264 }
1265
1266 static int
1267 syncprov_op_extended( Operation *op, SlapReply *rs )
1268 {
1269         if ( exop_is_write( op ))
1270                 return syncprov_op_mod( op, rs );
1271
1272         return SLAP_CB_CONTINUE;
1273 }
1274
1275 typedef struct searchstate {
1276         slap_overinst *ss_on;
1277         syncops *ss_so;
1278 } searchstate;
1279
1280 static int
1281 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1282 {
1283         if ( rs->sr_ctrls ) {
1284                 op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
1285                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1286                 rs->sr_ctrls = NULL;
1287         }
1288         return 0;
1289 }
1290
1291 static void
1292 syncprov_detach_op( Operation *op, syncops *so )
1293 {
1294         Operation *op2;
1295         int i, alen = 0;
1296         size_t size;
1297         char *ptr;
1298
1299         /* count the search attrs */
1300         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1301                 alen += op->ors_attrs[i].an_name.bv_len + 1;
1302         }
1303         /* Make a new copy of the operation */
1304         size = sizeof(Operation) + sizeof(Opheader) +
1305                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
1306                 op->o_req_dn.bv_len + 1 +
1307                 op->o_req_ndn.bv_len + 1 +
1308                 op->o_ndn.bv_len + 1 +
1309                 so->s_filterstr.bv_len + 1;
1310         op2 = (Operation *)ch_malloc( size );
1311         *op2 = *op;
1312         op2->o_hdr = (Opheader *)(op2+1);
1313         *op2->o_hdr = *op->o_hdr;
1314         if ( i ) {
1315                 op2->ors_attrs = (AttributeName *)(op2->o_hdr + 1);
1316                 ptr = (char *)(op2->ors_attrs+i+1);
1317                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1318                         op2->ors_attrs[i] = op->ors_attrs[i];
1319                         op2->ors_attrs[i].an_name.bv_val = ptr;
1320                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
1321                 }
1322                 BER_BVZERO( &op2->ors_attrs[i].an_name );
1323         } else {
1324                 ptr = (char *)(op2->o_hdr + 1);
1325         }
1326         op2->o_ndn.bv_val = ptr;
1327         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
1328         op2->o_dn = op2->o_ndn;
1329         op2->o_req_dn.bv_val = ptr;
1330         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
1331         op2->o_req_ndn.bv_val = ptr;
1332         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
1333         op2->ors_filterstr.bv_val = ptr;
1334         strcpy( ptr, so->s_filterstr.bv_val );
1335         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
1336         op2->ors_filter = str2filter( ptr );
1337         op2->o_controls = NULL;
1338         op2->o_callback = NULL;
1339         so->s_op = op2;
1340
1341         /* Increment number of ops so that idletimeout ignores us */
1342         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1343         op->o_conn->c_n_ops_executing++;
1344         op->o_conn->c_n_ops_completed--;
1345         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1346 }
1347
1348 static int
1349 syncprov_search_response( Operation *op, SlapReply *rs )
1350 {
1351         searchstate *ss = op->o_callback->sc_private;
1352         slap_overinst *on = ss->ss_on;
1353         syncprov_info_t         *si = on->on_bi.bi_private;
1354         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
1355
1356         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
1357                 int i;
1358                 /* If we got a referral without a referral object, there's
1359                  * something missing that we cannot replicate. Just ignore it.
1360                  * The consumer will abort because we didn't send the expected
1361                  * control.
1362                  */
1363                 if ( !rs->sr_entry ) {
1364                         assert( rs->sr_entry );
1365                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
1366                         return SLAP_CB_CONTINUE;
1367                 }
1368                 if ( srs->sr_state.ctxcsn ) {
1369                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
1370                                 slap_schema.si_ad_entryCSN );
1371                         /* Don't send the ctx entry twice */
1372                         if ( bvmatch( &a->a_nvals[0], srs->sr_state.ctxcsn ))
1373                                 return LDAP_SUCCESS;
1374                 }
1375                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1376                         op->o_tmpmemctx );
1377                 rs->sr_ctrls[1] = NULL;
1378                 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
1379                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
1380         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
1381                 struct berval cookie;
1382
1383                 slap_compose_sync_cookie( op, &cookie,
1384                         &op->ors_filter->f_and->f_ava->aa_value,
1385                         srs->sr_state.sid, srs->sr_state.rid );
1386
1387                 /* Is this a regular refresh? */
1388                 if ( !ss->ss_so ) {
1389                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1390                                 op->o_tmpmemctx );
1391                         rs->sr_ctrls[1] = NULL;
1392                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
1393                                 0, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
1394                 } else {
1395                         int locked = 0;
1396                 /* It's RefreshAndPersist, transition to Persist phase */
1397                         syncprov_sendinfo( op, rs, rs->sr_nentries ?
1398                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
1399                                 &cookie, 1, NULL, 0 );
1400                         /* Flush any queued persist messages */
1401                         if ( ss->ss_so->s_res ) {
1402                                 syncres *sr, *srnext;
1403                                 Entry *e;
1404                                 opcookie opc;
1405
1406                                 opc.son = on;
1407                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
1408                                 locked = 1;
1409                                 for (sr = ss->ss_so->s_res; sr; sr=srnext) {
1410                                         int rc = LDAP_SUCCESS;
1411                                         srnext = sr->s_next;
1412                                         opc.sdn = sr->s_dn;
1413                                         opc.sndn = sr->s_ndn;
1414                                         opc.suuid = sr->s_uuid;
1415                                         opc.sctxcsn = sr->s_csn;
1416                                         opc.sreference = sr->s_isreference;
1417                                         e = NULL;
1418
1419                                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
1420                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1421                                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
1422                                                 op->o_bd->bd_info = (BackendInfo *)on;
1423                                         }
1424                                         if ( rc == LDAP_SUCCESS )
1425                                                 syncprov_sendresp( op, &opc, ss->ss_so, e,
1426                                                         sr->s_mode, 0 );
1427
1428                                         if ( e ) {
1429                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1430                                                 be_entry_release_r( op, e );
1431                                                 op->o_bd->bd_info = (BackendInfo *)on;
1432                                         }
1433                                         ch_free( sr );
1434                                 }
1435                                 ss->ss_so->s_res = NULL;
1436                                 ss->ss_so->s_restail = NULL;
1437                         }
1438
1439                         /* Turn off the refreshing flag */
1440                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
1441                         if ( locked )
1442                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
1443
1444                         /* Detach this Op from frontend control */
1445                         syncprov_detach_op( op, ss->ss_so );
1446
1447                         return LDAP_SUCCESS;
1448                 }
1449         }
1450
1451         return SLAP_CB_CONTINUE;
1452 }
1453
1454 static int
1455 syncprov_op_search( Operation *op, SlapReply *rs )
1456 {
1457         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1458         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1459         slap_callback   *cb;
1460         int gotstate = 0, nochange = 0;
1461         Filter *fand, *fava;
1462         syncops *sop = NULL;
1463         searchstate *ss;
1464         sync_control *srs;
1465
1466         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
1467
1468         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1469                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
1470                 return rs->sr_err;
1471         }
1472
1473         srs = op->o_controls[slap_cids.sc_LDAPsync];
1474
1475         /* If this is a persistent search, set it up right away */
1476         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
1477                 syncops so = {0};
1478                 fbase_cookie fc;
1479                 opcookie opc;
1480                 slap_callback sc;
1481
1482                 fc.fss = &so;
1483                 fc.fbase = 0;
1484                 so.s_eid = NOID;
1485                 so.s_op = op;
1486                 so.s_flags = PS_IS_REFRESHING;
1487                 /* syncprov_findbase expects to be called as a callback... */
1488                 sc.sc_private = &opc;
1489                 opc.son = on;
1490                 cb = op->o_callback;
1491                 op->o_callback = &sc;
1492                 rs->sr_err = syncprov_findbase( op, &fc );
1493                 op->o_callback = cb;
1494
1495                 if ( rs->sr_err != LDAP_SUCCESS ) {
1496                         send_ldap_result( op, rs );
1497                         return rs->sr_err;
1498                 }
1499                 sop = ch_malloc( sizeof( syncops ));
1500                 *sop = so;
1501                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
1502                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1503                 sop->s_sid = srs->sr_state.sid;
1504                 sop->s_rid = srs->sr_state.rid;
1505                 sop->s_next = si->si_ops;
1506                 sop->s_inuse = 1;
1507                 si->si_ops = sop;
1508                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1509         }
1510
1511         /* If we have a cookie, handle the PRESENT lookups
1512          */
1513         if ( srs->sr_state.ctxcsn ) {
1514                 /* Is the CSN in a valid format? */
1515                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
1516                         send_ldap_error( op, rs, LDAP_OTHER, "invalid sync cookie" );
1517                         return rs->sr_err;
1518                 }
1519                 /* If just Refreshing and nothing has changed, shortcut it */
1520                 if ( bvmatch( srs->sr_state.ctxcsn, &si->si_ctxcsn )) {
1521                         nochange = 1;
1522                         if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
1523                                 LDAPControl     *ctrls[2];
1524
1525                                 ctrls[0] = NULL;
1526                                 ctrls[1] = NULL;
1527                                 syncprov_done_ctrl( op, rs, ctrls, 0, 0,
1528                                         NULL, LDAP_SYNC_REFRESH_DELETES );
1529                                 rs->sr_ctrls = ctrls;
1530                                 rs->sr_err = LDAP_SUCCESS;
1531                                 send_ldap_result( op, rs );
1532                                 rs->sr_ctrls = NULL;
1533                                 return rs->sr_err;
1534                         }
1535                         goto shortcut;
1536                 }
1537                 /* Is the CSN still present in the database? */
1538                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
1539                         /* No, so a reload is required */
1540 #if 0           /* the consumer doesn't seem to send this hint */
1541                         if ( op->o_sync_rhint == 0 ) {
1542                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
1543                                 return rs->sr_err;
1544                         }
1545 #endif
1546                 } else {
1547                         gotstate = 1;
1548                         /* If context has changed, check for Present UUIDs */
1549                         if ( syncprov_findcsn( op, FIND_PRESENT ) != LDAP_SUCCESS ) {
1550                                 send_ldap_result( op, rs );
1551                                 return rs->sr_err;
1552                         }
1553                 }
1554         }
1555
1556         /* Append CSN range to search filter, save original filter
1557          * for persistent search evaluation
1558          */
1559         if ( sop ) {
1560                 sop->s_filterstr= op->ors_filterstr;
1561         }
1562
1563         fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1564         fand->f_choice = LDAP_FILTER_AND;
1565         fand->f_next = NULL;
1566         fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1567         fava->f_choice = LDAP_FILTER_LE;
1568         fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1569         fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1570         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1571         ber_dupbv_x( &fava->f_ava->aa_value, &si->si_ctxcsn, op->o_tmpmemctx );
1572         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1573         fand->f_and = fava;
1574         if ( gotstate ) {
1575                 fava->f_next = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1576                 fava = fava->f_next;
1577                 fava->f_choice = LDAP_FILTER_GE;
1578                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1579                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1580                 ber_dupbv_x( &fava->f_ava->aa_value, srs->sr_state.ctxcsn, op->o_tmpmemctx );
1581         }
1582         fava->f_next = op->ors_filter;
1583         op->ors_filter = fand;
1584         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1585
1586 shortcut:
1587         /* Let our callback add needed info to returned entries */
1588         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1589         ss = (searchstate *)(cb+1);
1590         ss->ss_on = on;
1591         ss->ss_so = sop;
1592         cb->sc_response = syncprov_search_response;
1593         cb->sc_cleanup = syncprov_search_cleanup;
1594         cb->sc_private = ss;
1595         cb->sc_next = op->o_callback;
1596         op->o_callback = cb;
1597
1598 #if 0   /* I don't think we need to shortcircuit back-bdb any more */
1599         op->o_sync_mode &= SLAP_CONTROL_MASK;
1600 #endif
1601
1602         /* If this is a persistent search and no changes were reported during
1603          * the refresh phase, just invoke the response callback to transition
1604          * us into persist phase
1605          */
1606         if ( nochange ) {
1607                 rs->sr_err = LDAP_SUCCESS;
1608                 rs->sr_nentries = 0;
1609                 send_ldap_result( op, rs );
1610                 return rs->sr_err;
1611         }
1612         return SLAP_CB_CONTINUE;
1613 }
1614
1615 static int
1616 syncprov_operational(
1617         Operation *op,
1618         SlapReply *rs )
1619 {
1620         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1621         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1622
1623         if ( rs->sr_entry &&
1624                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
1625
1626                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
1627                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
1628                         Attribute *a, **ap = NULL;
1629
1630                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
1631                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
1632                                         break;
1633                         }
1634
1635                         if ( !a ) {
1636                                 for ( ap = &rs->sr_operational_attrs; *ap; ap=&(*ap)->a_next );
1637
1638                                 a = ch_malloc( sizeof(Attribute));
1639                                 a->a_desc = slap_schema.si_ad_contextCSN;
1640                                 a->a_vals = ch_malloc( 2 * sizeof(struct berval));
1641                                 a->a_vals[1].bv_val = NULL;
1642                                 a->a_nvals = a->a_vals;
1643                                 a->a_next = NULL;
1644                                 a->a_flags = 0;
1645                                 *ap = a;
1646                         }
1647
1648                         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1649                         if ( !ap ) {
1650                                 strcpy( a->a_vals[0].bv_val, si->si_ctxcsnbuf );
1651                         } else {
1652                                 ber_dupbv( &a->a_vals[0], &si->si_ctxcsn );
1653                         }
1654                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1655                 }
1656         }
1657         return SLAP_CB_CONTINUE;
1658 }
1659
1660 static int
1661 syncprov_db_config(
1662         BackendDB       *be,
1663         const char      *fname,
1664         int             lineno,
1665         int             argc,
1666         char    **argv
1667 )
1668 {
1669         slap_overinst           *on = (slap_overinst *)be->bd_info;
1670         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1671
1672         if ( strcasecmp( argv[ 0 ], "syncprov-checkpoint" ) == 0 ) {
1673                 if ( argc != 3 ) {
1674                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1675                                 "\"syncprov-checkpoint <ops> <minutes>\"\n", fname, lineno );
1676                         return -1;
1677                 }
1678                 si->si_chkops = atoi( argv[1] );
1679                 si->si_chktime = atoi( argv[2] ) * 60;
1680                 return 0;
1681
1682         }
1683
1684         return SLAP_CONF_UNKNOWN;
1685 }
1686
1687 /* Cheating - we have no thread pool context for these functions,
1688  * so make one.
1689  */
1690 typedef struct thread_keys {
1691         void *key;
1692         void *data;
1693         ldap_pvt_thread_pool_keyfree_t *xfree;
1694 } thread_keys;
1695
1696 #define MAXKEYS 32
1697 /* A fake thread context */
1698 static thread_keys thrctx[MAXKEYS];
1699
1700 /* Read any existing contextCSN from the underlying db.
1701  * Then search for any entries newer than that. If no value exists,
1702  * just generate it. Cache whatever result.
1703  */
1704 static int
1705 syncprov_db_open(
1706     BackendDB *be
1707 )
1708 {
1709         slap_overinst   *on = (slap_overinst *) be->bd_info;
1710         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1711
1712         Connection conn;
1713         char opbuf[OPERATION_BUFFER_SIZE];
1714         char ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1715         Operation *op = (Operation *)opbuf;
1716         Entry *e;
1717         Attribute *a;
1718         int rc;
1719
1720         connection_fake_init( &conn, op, thrctx );
1721         op->o_bd = be;
1722         op->o_dn = be->be_rootdn;
1723         op->o_ndn = be->be_rootndn;
1724
1725         ctxcsnbuf[0] = '\0';
1726
1727         op->o_bd->bd_info = on->on_info->oi_orig;
1728         rc = be_entry_get_rw( op, be->be_nsuffix, NULL,
1729                 slap_schema.si_ad_contextCSN, 0, &e );
1730
1731         if ( e ) {
1732                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
1733                 if ( a ) {
1734                         si->si_ctxcsn.bv_len = a->a_nvals[0].bv_len;
1735                         if ( si->si_ctxcsn.bv_len >= sizeof(si->si_ctxcsnbuf ))
1736                                 si->si_ctxcsn.bv_len = sizeof(si->si_ctxcsnbuf)-1;
1737                         strncpy( si->si_ctxcsnbuf, a->a_nvals[0].bv_val,
1738                                 si->si_ctxcsn.bv_len );
1739                         si->si_ctxcsnbuf[si->si_ctxcsn.bv_len] = '\0';
1740                         strcpy( ctxcsnbuf, si->si_ctxcsnbuf );
1741                 }
1742                 be_entry_release_r( op, e );
1743                 op->o_bd->bd_info = (BackendInfo *)on;
1744                 op->o_req_dn = be->be_suffix[0];
1745                 op->o_req_ndn = be->be_nsuffix[0];
1746                 op->ors_scope = LDAP_SCOPE_SUBTREE;
1747                 syncprov_findcsn( op, FIND_MAXCSN );
1748         }
1749
1750         if ( BER_BVISEMPTY( &si->si_ctxcsn ) ) {
1751                 slap_get_csn( op, si->si_ctxcsnbuf, sizeof(si->si_ctxcsnbuf),
1752                                 &si->si_ctxcsn, 0 );
1753         }
1754
1755         /* If our ctxcsn is different from what was read from the root
1756          * entry, write the new value out.
1757          */
1758         if ( strcmp( si->si_ctxcsnbuf, ctxcsnbuf )) {
1759                 SlapReply rs = {REP_RESULT};
1760                 syncprov_checkpoint( op, &rs, on );
1761         }
1762
1763         op->o_bd->bd_info = (BackendInfo *)on;
1764         return 0;
1765 }
1766
1767 /* Write the current contextCSN into the underlying db.
1768  */
1769 static int
1770 syncprov_db_close(
1771     BackendDB *be
1772 )
1773 {
1774     slap_overinst   *on = (slap_overinst *) be->bd_info;
1775     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1776         int i;
1777
1778         if ( si->si_numops ) {
1779                 Connection conn;
1780                 char opbuf[OPERATION_BUFFER_SIZE];
1781                 Operation *op = (Operation *)opbuf;
1782                 SlapReply rs = {REP_RESULT};
1783
1784                 connection_fake_init( &conn, op, thrctx );
1785                 op->o_bd = be;
1786                 op->o_dn = be->be_rootdn;
1787                 op->o_ndn = be->be_rootndn;
1788                 syncprov_checkpoint( op, &rs, on );
1789         }
1790         for ( i=0; thrctx[i].key; i++) {
1791                 if ( thrctx[i].xfree )
1792                         thrctx[i].xfree( thrctx[i].key, thrctx[i].data );
1793                 thrctx[i].key = NULL;
1794         }
1795
1796     return 0;
1797 }
1798
1799 static int
1800 syncprov_db_init(
1801         BackendDB *be
1802 )
1803 {
1804         slap_overinst   *on = (slap_overinst *)be->bd_info;
1805         syncprov_info_t *si;
1806
1807         si = ch_calloc(1, sizeof(syncprov_info_t));
1808         on->on_bi.bi_private = si;
1809         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
1810         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
1811         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
1812         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
1813
1814         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
1815         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
1816
1817         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
1818         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1819
1820         return 0;
1821 }
1822
1823 static int
1824 syncprov_db_destroy(
1825         BackendDB *be
1826 )
1827 {
1828         slap_overinst   *on = (slap_overinst *)be->bd_info;
1829         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1830
1831         if ( si ) {
1832                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
1833                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
1834                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
1835                 ch_free( si );
1836         }
1837
1838         return 0;
1839 }
1840
1841 static int syncprov_parseCtrl (
1842         Operation *op,
1843         SlapReply *rs,
1844         LDAPControl *ctrl )
1845 {
1846         ber_tag_t tag;
1847         BerElement *ber;
1848         ber_int_t mode;
1849         ber_len_t len;
1850         struct berval cookie = BER_BVNULL;
1851         sync_control *sr;
1852         int rhint = 0;
1853
1854         if ( op->o_sync != SLAP_CONTROL_NONE ) {
1855                 rs->sr_text = "Sync control specified multiple times";
1856                 return LDAP_PROTOCOL_ERROR;
1857         }
1858
1859         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
1860                 rs->sr_text = "Sync control specified with pagedResults control";
1861                 return LDAP_PROTOCOL_ERROR;
1862         }
1863
1864         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1865                 rs->sr_text = "Sync control value is empty (or absent)";
1866                 return LDAP_PROTOCOL_ERROR;
1867         }
1868
1869         /* Parse the control value
1870          *      syncRequestValue ::= SEQUENCE {
1871          *              mode   ENUMERATED {
1872          *                      -- 0 unused
1873          *                      refreshOnly             (1),
1874          *                      -- 2 reserved
1875          *                      refreshAndPersist       (3)
1876          *              },
1877          *              cookie  syncCookie OPTIONAL
1878          *      }
1879          */
1880
1881         ber = ber_init( &ctrl->ldctl_value );
1882         if( ber == NULL ) {
1883                 rs->sr_text = "internal error";
1884                 return LDAP_OTHER;
1885         }
1886
1887         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
1888                 rs->sr_text = "Sync control : mode decoding error";
1889                 return LDAP_PROTOCOL_ERROR;
1890         }
1891
1892         switch( mode ) {
1893         case LDAP_SYNC_REFRESH_ONLY:
1894                 mode = SLAP_SYNC_REFRESH;
1895                 break;
1896         case LDAP_SYNC_REFRESH_AND_PERSIST:
1897                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
1898                 break;
1899         default:
1900                 rs->sr_text = "Sync control : unknown update mode";
1901                 return LDAP_PROTOCOL_ERROR;
1902         }
1903
1904         tag = ber_peek_tag( ber, &len );
1905
1906         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
1907                 if (( ber_scanf( ber, /*{*/ "o", &cookie )) == LBER_ERROR ) {
1908                         rs->sr_text = "Sync control : cookie decoding error";
1909                         return LDAP_PROTOCOL_ERROR;
1910                 }
1911         }
1912         if ( tag == LDAP_TAG_RELOAD_HINT ) {
1913                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
1914                         rs->sr_text = "Sync control : rhint decoding error";
1915                         return LDAP_PROTOCOL_ERROR;
1916                 }
1917         }
1918         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
1919                         rs->sr_text = "Sync control : decoding error";
1920                         return LDAP_PROTOCOL_ERROR;
1921         }
1922         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
1923         sr->sr_rhint = rhint;
1924         if (!BER_BVISNULL(&cookie)) {
1925                 ber_bvarray_add( &sr->sr_state.octet_str, &cookie );
1926                 slap_parse_sync_cookie( &sr->sr_state );
1927         }
1928
1929         op->o_controls[slap_cids.sc_LDAPsync] = sr;
1930
1931         (void) ber_free( ber, 1 );
1932
1933         op->o_sync = ctrl->ldctl_iscritical
1934                 ? SLAP_CONTROL_CRITICAL
1935                 : SLAP_CONTROL_NONCRITICAL;
1936
1937         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
1938
1939         return LDAP_SUCCESS;
1940 }
1941
1942 /* This overlay is set up for dynamic loading via moduleload. For static
1943  * configuration, you'll need to arrange for the slap_overinst to be
1944  * initialized and registered by some other function inside slapd.
1945  */
1946
1947 static slap_overinst            syncprov;
1948
1949 int
1950 syncprov_init()
1951 {
1952         int rc;
1953
1954         rc = register_supported_control( LDAP_CONTROL_SYNC,
1955                 SLAP_CTRL_HIDE|SLAP_CTRL_SEARCH, NULL,
1956                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
1957         if ( rc != LDAP_SUCCESS ) {
1958                 fprintf( stderr, "Failed to register control %d\n", rc );
1959                 return rc;
1960         }
1961
1962         syncprov.on_bi.bi_type = "syncprov";
1963         syncprov.on_bi.bi_db_init = syncprov_db_init;
1964         syncprov.on_bi.bi_db_config = syncprov_db_config;
1965         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
1966         syncprov.on_bi.bi_db_open = syncprov_db_open;
1967         syncprov.on_bi.bi_db_close = syncprov_db_close;
1968
1969         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
1970         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
1971
1972         syncprov.on_bi.bi_op_add = syncprov_op_mod;
1973         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
1974         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
1975         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
1976         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
1977         syncprov.on_bi.bi_op_search = syncprov_op_search;
1978         syncprov.on_bi.bi_extended = syncprov_op_extended;
1979         syncprov.on_bi.bi_operational = syncprov_operational;
1980
1981         return overlay_register( &syncprov );
1982 }
1983
1984 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
1985 int
1986 init_module( int argc, char *argv[] )
1987 {
1988         return syncprov_init();
1989 }
1990 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
1991
1992 #endif /* defined(SLAPD_OVER_SYNCPROV) */