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