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