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