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