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