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