]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
Rearrange shortcut check for context with no changes
[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 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
29 /* A modify request on a particular entry */
30 typedef struct modinst {
31         struct modinst *mi_next;
32         Operation *mi_op;
33 } modinst;
34
35 typedef struct modtarget {
36         struct modinst *mt_mods;
37         struct modinst *mt_tail;
38         Operation *mt_op;
39         ldap_pvt_thread_mutex_t mt_mutex;
40 } modtarget;
41
42 /* A queued result of a persistent search */
43 typedef struct syncres {
44         struct syncres *s_next;
45         struct berval s_dn;
46         struct berval s_ndn;
47         struct berval s_uuid;
48         struct berval s_csn;
49         char s_mode;
50         char s_isreference;
51 } syncres;
52
53 /* Record of a persistent search */
54 typedef struct syncops {
55         struct syncops *s_next;
56         struct berval   s_base;         /* ndn of search base */
57         ID              s_eid;          /* entryID of search base */
58         Operation       *s_op;          /* search op */
59         long    s_sid;
60         long    s_rid;
61         struct berval s_filterstr;
62         int             s_flags;        /* search status */
63         int             s_inuse;        /* reference count */
64         struct syncres *s_res;
65         struct syncres *s_restail;
66         ldap_pvt_thread_mutex_t s_mutex;
67 } syncops;
68
69 /* A received sync control */
70 typedef struct sync_control {
71         struct sync_cookie sr_state;
72         int sr_rhint;
73 } sync_control;
74
75 #if 0 /* moved back to slap.h */
76 #define o_sync  o_ctrlflag[slap_cids.sc_LDAPsync]
77 #endif
78 /* o_sync_mode uses data bits of o_sync */
79 #define o_sync_mode     o_ctrlflag[slap_cids.sc_LDAPsync]
80
81 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
82 #define SLAP_SYNC_REFRESH                               (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
83 #define SLAP_SYNC_PERSIST                               (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
84 #define SLAP_SYNC_REFRESH_AND_PERSIST   (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
85
86 #define PS_IS_REFRESHING        0x01
87
88 /* Record of which searches matched at premodify step */
89 typedef struct syncmatches {
90         struct syncmatches *sm_next;
91         syncops *sm_op;
92 } syncmatches;
93
94 /* The main state for this overlay */
95 typedef struct syncprov_info_t {
96         syncops         *si_ops;
97         struct berval   si_ctxcsn;      /* ldapsync context */
98         int             si_chkops;      /* checkpointing info */
99         int             si_chktime;
100         int             si_numops;      /* number of ops since last checkpoint */
101         time_t  si_chklast;     /* time of last checkpoint */
102         Avlnode *si_mods;       /* entries being modified */
103         ldap_pvt_thread_mutex_t si_csn_mutex;
104         ldap_pvt_thread_mutex_t si_ops_mutex;
105         ldap_pvt_thread_mutex_t si_mods_mutex;
106         char            si_ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
107 } syncprov_info_t;
108
109 typedef struct opcookie {
110         slap_overinst *son;
111         syncmatches *smatches;
112         struct berval sdn;      /* DN of entry, for deletes */
113         struct berval sndn;
114         struct berval suuid;    /* UUID of entry */
115         struct berval sctxcsn;
116         int sreference; /* Is the entry a reference? */
117 } opcookie;
118
119 typedef struct fbase_cookie {
120         struct berval *fdn;     /* DN of a modified entry, for scope testing */
121         syncops *fss;   /* persistent search we're testing against */
122         int fbase;      /* if TRUE we found the search base and it's still valid */
123         int fscope;     /* if TRUE then fdn is within the psearch scope */
124 } fbase_cookie;
125
126 static AttributeName csn_anlist[2];
127 static AttributeName uuid_anlist[2];
128
129 /* Build a LDAPsync intermediate state control */
130 static int
131 syncprov_state_ctrl(
132         Operation       *op,
133         SlapReply       *rs,
134         Entry           *e,
135         int             entry_sync_state,
136         LDAPControl     **ctrls,
137         int             num_ctrls,
138         int             send_cookie,
139         struct berval   *cookie )
140 {
141         Attribute* a;
142         int ret;
143         int res;
144         const char *text = NULL;
145
146         BerElementBuffer berbuf;
147         BerElement *ber = (BerElement *)&berbuf;
148
149         struct berval   entryuuid_bv = BER_BVNULL;
150
151         ber_init2( ber, 0, LBER_USE_DER );
152         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
153
154         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
155
156         for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
157                 AttributeDescription *desc = a->a_desc;
158                 if ( desc == slap_schema.si_ad_entryUUID ) {
159                         entryuuid_bv = a->a_nvals[0];
160                         break;
161                 }
162         }
163
164         if ( send_cookie && cookie ) {
165                 ber_printf( ber, "{eOON}",
166                         entry_sync_state, &entryuuid_bv, cookie );
167         } else {
168                 ber_printf( ber, "{eON}",
169                         entry_sync_state, &entryuuid_bv );
170         }
171
172         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
173         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
174         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
175
176         ber_free_buf( ber );
177
178         if ( ret < 0 ) {
179                 Debug( LDAP_DEBUG_TRACE,
180                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
181                         0, 0, 0 );
182                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
183                 return ret;
184         }
185
186         return LDAP_SUCCESS;
187 }
188
189 /* Build a LDAPsync final state control */
190 static int
191 syncprov_done_ctrl(
192         Operation       *op,
193         SlapReply       *rs,
194         LDAPControl     **ctrls,
195         int                     num_ctrls,
196         int                     send_cookie,
197         struct berval *cookie,
198         int                     refreshDeletes )
199 {
200         int ret;
201         BerElementBuffer berbuf;
202         BerElement *ber = (BerElement *)&berbuf;
203
204         ber_init2( ber, NULL, LBER_USE_DER );
205         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
206
207         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
208
209         ber_printf( ber, "{" );
210         if ( send_cookie && cookie ) {
211                 ber_printf( ber, "O", cookie );
212         }
213         if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
214                 ber_printf( ber, "b", refreshDeletes );
215         }
216         ber_printf( ber, "N}" );
217
218         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
219         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
220         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
221
222         ber_free_buf( ber );
223
224         if ( ret < 0 ) {
225                 Debug( LDAP_DEBUG_TRACE,
226                         "syncprov_done_ctrl: ber_flatten2 failed\n",
227                         0, 0, 0 );
228                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
229                 return ret;
230         }
231
232         return LDAP_SUCCESS;
233 }
234
235 #if 0
236 /* Generate state based on session log - not implemented yet */
237 static int
238 syncprov_state_ctrl_from_slog(
239         Operation       *op,
240         SlapReply       *rs,
241         struct slog_entry *slog_e,
242         int                     entry_sync_state,
243         LDAPControl     **ctrls,
244         int                     num_ctrls,
245         int                     send_cookie,
246         struct berval   *cookie)
247 {
248         Attribute* a;
249         int ret;
250         int res;
251         const char *text = NULL;
252
253         BerElementBuffer berbuf;
254         BerElement *ber = (BerElement *)&berbuf;
255
256         struct berval entryuuid_bv      = BER_BVNULL;
257
258         ber_init2( ber, NULL, LBER_USE_DER );
259         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
260
261         ctrls[num_ctrls] = ch_malloc ( sizeof ( LDAPControl ) );
262
263         entryuuid_bv = slog_e->sl_uuid;
264
265         if ( send_cookie && cookie ) {
266                 ber_printf( ber, "{eOON}",
267                         entry_sync_state, &entryuuid_bv, cookie );
268         } else {
269                 ber_printf( ber, "{eON}",
270                         entry_sync_state, &entryuuid_bv );
271         }
272
273         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
274         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
275         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
276
277         ber_free_buf( ber );
278
279         if ( ret < 0 ) {
280                 Debug( LDAP_DEBUG_TRACE,
281                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
282                         0, 0, 0 );
283                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
284                 return ret;
285         }
286
287         return LDAP_SUCCESS;
288 }
289 #endif
290
291 static int
292 syncprov_sendinfo(
293         Operation       *op,
294         SlapReply       *rs,
295         int                     type,
296         struct berval *cookie,
297         int                     refreshDone,
298         BerVarray       syncUUIDs,
299         int                     refreshDeletes )
300 {
301         BerElementBuffer berbuf;
302         BerElement *ber = (BerElement *)&berbuf;
303         struct berval rspdata;
304
305         int ret;
306
307         ber_init2( ber, NULL, LBER_USE_DER );
308         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
309
310         if ( type ) {
311                 switch ( type ) {
312                 case LDAP_TAG_SYNC_NEW_COOKIE:
313                         ber_printf( ber, "tO", type, cookie );
314                         break;
315                 case LDAP_TAG_SYNC_REFRESH_DELETE:
316                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
317                         ber_printf( ber, "t{", type );
318                         if ( cookie ) {
319                                 ber_printf( ber, "O", cookie );
320                         }
321                         if ( refreshDone == 0 ) {
322                                 ber_printf( ber, "b", refreshDone );
323                         }
324                         ber_printf( ber, "N}" );
325                         break;
326                 case LDAP_TAG_SYNC_ID_SET:
327                         ber_printf( ber, "t{", type );
328                         if ( cookie ) {
329                                 ber_printf( ber, "O", cookie );
330                         }
331                         if ( refreshDeletes == 1 ) {
332                                 ber_printf( ber, "b", refreshDeletes );
333                         }
334                         ber_printf( ber, "[W]", syncUUIDs );
335                         ber_printf( ber, "N}" );
336                         break;
337                 default:
338                         Debug( LDAP_DEBUG_TRACE,
339                                 "syncprov_sendinfo: invalid syncinfo type (%d)\n",
340                                 type, 0, 0 );
341                         return LDAP_OTHER;
342                 }
343         }
344
345         ret = ber_flatten2( ber, &rspdata, 0 );
346
347         if ( ret < 0 ) {
348                 Debug( LDAP_DEBUG_TRACE,
349                         "syncprov_sendinfo: ber_flatten2 failed\n",
350                         0, 0, 0 );
351                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
352                 return ret;
353         }
354
355         rs->sr_rspoid = LDAP_SYNC_INFO;
356         rs->sr_rspdata = &rspdata;
357         send_ldap_intermediate( op, rs );
358         rs->sr_rspdata = NULL;
359         ber_free_buf( ber );
360
361         return LDAP_SUCCESS;
362 }
363
364 /* Find a modtarget in an AVL tree */
365 static int
366 sp_avl_cmp( const void *c1, const void *c2 )
367 {
368         const modtarget *m1, *m2;
369         int rc;
370
371         m1 = c1; m2 = c2;
372         rc = m1->mt_op->o_req_ndn.bv_len - m2->mt_op->o_req_ndn.bv_len;
373
374         if ( rc ) return rc;
375         return ber_bvcmp( &m1->mt_op->o_req_ndn, &m2->mt_op->o_req_ndn );
376 }
377
378 /* syncprov_findbase:
379  *   finds the true DN of the base of a search (with alias dereferencing) and
380  * checks to make sure the base entry doesn't get replaced with a different
381  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
382  * change is detected, any persistent search on this base must be terminated /
383  * reloaded.
384  *   On the first call, we just save the DN and entryID. On subsequent calls
385  * we compare the DN and entryID with the saved values.
386  */
387 static int
388 findbase_cb( Operation *op, SlapReply *rs )
389 {
390         slap_callback *sc = op->o_callback;
391
392         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
393                 fbase_cookie *fc = sc->sc_private;
394
395                 /* If no entryID, we're looking for the first time.
396                  * Just store whatever we got.
397                  */
398                 if ( fc->fss->s_eid == NOID ) {
399                         fc->fbase = 1;
400                         fc->fss->s_eid = rs->sr_entry->e_id;
401                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
402
403                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
404                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
405
406                 /* OK, the DN is the same and the entryID is the same. Now
407                  * see if the fdn resides in the scope.
408                  */
409                         fc->fbase = 1;
410                         switch ( fc->fss->s_op->ors_scope ) {
411                         case LDAP_SCOPE_BASE:
412                                 fc->fscope = dn_match( fc->fdn, &rs->sr_entry->e_nname );
413                                 break;
414                         case LDAP_SCOPE_ONELEVEL: {
415                                 struct berval pdn;
416                                 dnParent( fc->fdn, &pdn );
417                                 fc->fscope = dn_match( &pdn, &rs->sr_entry->e_nname );
418                                 break; }
419                         case LDAP_SCOPE_SUBTREE:
420                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname );
421                                 break;
422 #ifdef LDAP_SCOPE_SUBORDINATE
423                         case LDAP_SCOPE_SUBORDINATE:
424                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname ) &&
425                                         !dn_match( fc->fdn, &rs->sr_entry->e_nname );
426                                 break;
427 #endif
428                         }
429                 }
430         }
431         if ( rs->sr_err != LDAP_SUCCESS ) {
432                 Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err,0,0 );
433         }
434         return LDAP_SUCCESS;
435 }
436
437 static int
438 syncprov_findbase( Operation *op, fbase_cookie *fc )
439 {
440         opcookie *opc = op->o_callback->sc_private;
441         slap_overinst *on = opc->son;
442         syncprov_info_t         *si = on->on_bi.bi_private;
443
444         slap_callback cb = {0};
445         Operation fop;
446         SlapReply frs = { REP_RESULT };
447         int rc;
448
449         fop = *op;
450
451         cb.sc_response = findbase_cb;
452         cb.sc_private = fc;
453
454         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync mode */
455         fop.o_callback = &cb;
456         fop.o_tag = LDAP_REQ_SEARCH;
457         fop.ors_scope = LDAP_SCOPE_BASE;
458         fop.ors_deref = fc->fss->s_op->ors_deref;
459         fop.ors_limit = NULL;
460         fop.ors_slimit = 1;
461         fop.ors_tlimit = SLAP_NO_LIMIT;
462         fop.ors_attrs = slap_anlist_no_attrs;
463         fop.ors_attrsonly = 1;
464         fop.ors_filter = fc->fss->s_op->ors_filter;
465         fop.ors_filterstr = fc->fss->s_op->ors_filterstr;
466
467         fop.o_req_ndn = fc->fss->s_op->o_req_ndn;
468
469         fop.o_bd->bd_info = on->on_info->oi_orig;
470         rc = fop.o_bd->be_search( &fop, &frs );
471         fop.o_bd->bd_info = (BackendInfo *)on;
472
473         if ( fc->fbase ) return LDAP_SUCCESS;
474
475         /* If entryID has changed, then the base of this search has
476          * changed. Invalidate the psearch.
477          */
478         return LDAP_NO_SUCH_OBJECT;
479 }
480
481 /* syncprov_findcsn:
482  *   This function has three different purposes, but they all use a search
483  * that filters on entryCSN so they're combined here.
484  * 1: at startup time, after a contextCSN has been read from the database,
485  * we search for all entries with CSN >= contextCSN in case the contextCSN
486  * was not checkpointed at the previous shutdown.
487  *
488  * 2: when the current contextCSN is known and we have a sync cookie, we search
489  * for one entry with CSN <= the cookie CSN. (Used to search for =.) If an
490  * entry is found, the cookie CSN is valid, otherwise it is stale.
491  *
492  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
493  * CSN, and generate Present records for them. We always collect this result
494  * in SyncID sets, even if there's only one match.
495  */
496 #define FIND_MAXCSN     1
497 #define FIND_CSN        2
498 #define FIND_PRESENT    3
499
500 static int
501 findmax_cb( Operation *op, SlapReply *rs )
502 {
503         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
504                 struct berval *maxcsn = op->o_callback->sc_private;
505                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
506                         slap_schema.si_ad_entryCSN );
507
508                 if ( a && ber_bvcmp( &a->a_vals[0], maxcsn )) {
509                         maxcsn->bv_len = a->a_vals[0].bv_len;
510                         strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
511                 }
512         }
513         return LDAP_SUCCESS;
514 }
515
516 static int
517 findcsn_cb( Operation *op, SlapReply *rs )
518 {
519         slap_callback *sc = op->o_callback;
520
521         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
522                 sc->sc_private = (void *)1;
523         }
524         return LDAP_SUCCESS;
525 }
526
527 /* Build a list of entryUUIDs for sending in a SyncID set */
528
529 #define UUID_LEN        16
530
531 typedef struct fpres_cookie {
532         int num;
533         BerVarray uuids;
534         char *last;
535 } fpres_cookie;
536
537 static int
538 findpres_cb( Operation *op, SlapReply *rs )
539 {
540         slap_callback *sc = op->o_callback;
541         fpres_cookie *pc = sc->sc_private;
542         int ret = SLAP_CB_CONTINUE;
543
544         if ( rs->sr_type == REP_SEARCH ) {
545                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
546                         slap_schema.si_ad_entryUUID );
547                 if ( a ) {
548                         pc->uuids[pc->num].bv_val = pc->last;
549                         AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
550                                 pc->uuids[pc->num].bv_len );
551                         pc->num++;
552                         pc->last = pc->uuids[pc->num].bv_val;
553                         pc->uuids[pc->num].bv_val = NULL;
554                 }
555                 ret = LDAP_SUCCESS;
556                 if ( pc->num == SLAP_SYNCUUID_SET_SIZE ) {
557                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
558                                 0, pc->uuids, 0 );
559                         pc->uuids[pc->num].bv_val = pc->last;
560                         pc->num = 0;
561                         pc->last = pc->uuids[0].bv_val;
562                 }
563
564         } else if ( rs->sr_type == REP_RESULT ) {
565                 ret = rs->sr_err;
566                 if ( pc->num ) {
567                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
568                                 0, pc->uuids, 0 );
569                         pc->uuids[pc->num].bv_val = pc->last;
570                         pc->num = 0;
571                         pc->last = pc->uuids[0].bv_val;
572                 }
573         }
574         return ret;
575 }
576
577 static int
578 syncprov_findcsn( Operation *op, int mode )
579 {
580         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
581         syncprov_info_t         *si = on->on_bi.bi_private;
582
583         slap_callback cb = {0};
584         Operation fop;
585         SlapReply frs = { REP_RESULT };
586         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
587         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
588         struct berval fbuf, maxcsn;
589         Filter cf;
590         AttributeAssertion eq;
591         int i, rc = LDAP_SUCCESS;
592         fpres_cookie pcookie;
593         sync_control *srs;
594
595         if ( mode != FIND_MAXCSN ) {
596                 srs = op->o_controls[slap_cids.sc_LDAPsync];
597
598                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
599                         return LDAP_OTHER;
600                 }
601         }
602
603         fop = *op;
604         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
605
606         fbuf.bv_val = buf;
607         cf.f_ava = &eq;
608         cf.f_av_desc = slap_schema.si_ad_entryCSN;
609         cf.f_next = NULL;
610
611         switch( mode ) {
612         case FIND_MAXCSN:
613                 cf.f_choice = LDAP_FILTER_GE;
614                 cf.f_av_value = si->si_ctxcsn;
615                 fbuf.bv_len = sprintf( buf, "(entryCSN>=%s)",
616                         cf.f_av_value.bv_val );
617                 fop.ors_attrsonly = 0;
618                 fop.ors_attrs = csn_anlist;
619                 fop.ors_slimit = SLAP_NO_LIMIT;
620                 cb.sc_private = &maxcsn;
621                 cb.sc_response = findmax_cb;
622                 maxcsn.bv_val = cbuf;
623                 maxcsn.bv_len = 0;
624                 break;
625         case FIND_CSN:
626                 cf.f_choice = LDAP_FILTER_LE;
627                 cf.f_av_value = *srs->sr_state.ctxcsn;
628                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)",
629                         cf.f_av_value.bv_val );
630                 fop.ors_attrsonly = 1;
631                 fop.ors_attrs = slap_anlist_no_attrs;
632                 fop.ors_slimit = 1;
633                 cb.sc_private = NULL;
634                 cb.sc_response = findcsn_cb;
635                 break;
636         case FIND_PRESENT:
637                 cf.f_choice = LDAP_FILTER_LE;
638                 cf.f_av_value = *srs->sr_state.ctxcsn;
639                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)",
640                         cf.f_av_value.bv_val );
641                 fop.ors_attrsonly = 0;
642                 fop.ors_attrs = uuid_anlist;
643                 fop.ors_slimit = SLAP_NO_LIMIT;
644                 /* We want pure entries, not referrals */
645                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
646                 cb.sc_private = &pcookie;
647                 cb.sc_response = findpres_cb;
648                 pcookie.num = 0;
649
650                 /* preallocate storage for a full set */
651                 pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
652                         sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
653                         op->o_tmpmemctx );
654                 pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
655                 pcookie.uuids[0].bv_val = pcookie.last;
656                 pcookie.uuids[0].bv_len = UUID_LEN;
657                 for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
658                         pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
659                         pcookie.uuids[i].bv_len = UUID_LEN;
660                 }
661                 break;
662         }
663         fop.o_callback = &cb;
664         fop.ors_limit = NULL;
665         fop.ors_tlimit = SLAP_NO_LIMIT;
666         fop.ors_filter = &cf;
667         fop.ors_filterstr = fbuf;
668
669         fop.o_bd->bd_info = on->on_info->oi_orig;
670         fop.o_bd->be_search( &fop, &frs );
671         fop.o_bd->bd_info = (BackendInfo *)on;
672
673         switch( mode ) {
674         case FIND_MAXCSN:
675                 if ( maxcsn.bv_len ) {
676                         strcpy( si->si_ctxcsnbuf, maxcsn.bv_val );
677                         si->si_ctxcsn.bv_len = maxcsn.bv_len;
678                 }
679                 break;
680         case FIND_CSN:
681                 /* If matching CSN was not found, invalidate the context. */
682                 if ( !cb.sc_private ) rc = LDAP_NO_SUCH_OBJECT;
683                 break;
684         case FIND_PRESENT:
685                 op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
686                 break;
687         }
688
689         return rc;
690 }
691
692 /* Queue a persistent search response if still in Refresh stage */
693 static int
694 syncprov_qresp( opcookie *opc, syncops *so, int mode )
695 {
696         syncres *sr;
697
698         sr = ch_malloc(sizeof(syncres) + opc->suuid.bv_len + 1 +
699                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1 + opc->sctxcsn.bv_len + 1 );
700         sr->s_next = NULL;
701         sr->s_dn.bv_val = (char *)(sr + 1);
702         sr->s_mode = mode;
703         sr->s_isreference = opc->sreference;
704         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val, opc->sdn.bv_val );
705         *(sr->s_ndn.bv_val++) = '\0';
706         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val, opc->sndn.bv_val );
707         *(sr->s_uuid.bv_val++) = '\0';
708         sr->s_csn.bv_val = lutil_strcopy( sr->s_uuid.bv_val, opc->suuid.bv_val );
709
710         if ( !so->s_res ) {
711                 so->s_res = sr;
712         } else {
713                 so->s_restail->s_next = sr;
714         }
715         so->s_restail = sr;
716         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
717         return LDAP_SUCCESS;
718 }
719
720 /* Send a persistent search response */
721 static int
722 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, Entry *e, int mode, int queue )
723 {
724         slap_overinst *on = opc->son;
725         syncprov_info_t *si = on->on_bi.bi_private;
726
727         SlapReply rs = { REP_SEARCH };
728         LDAPControl *ctrls[2];
729         struct berval cookie;
730         Entry e_uuid = {0};
731         Attribute a_uuid = {0};
732         Operation sop = *so->s_op;
733         Opheader ohdr;
734
735         ohdr = *sop.o_hdr;
736         sop.o_hdr = &ohdr;
737         sop.o_tmpmemctx = op->o_tmpmemctx;
738         sop.o_bd = op->o_bd;
739         sop.o_controls = op->o_controls;
740
741         if ( queue && (so->s_flags & PS_IS_REFRESHING) ) {
742                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
743                 if ( so->s_flags & PS_IS_REFRESHING )
744                         return syncprov_qresp( opc, so, mode );
745                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
746         }
747
748         ctrls[1] = NULL;
749         slap_compose_sync_cookie( op, &cookie, &opc->sctxcsn,
750                 so->s_sid, so->s_rid );
751
752         e_uuid.e_attrs = &a_uuid;
753         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
754         a_uuid.a_nvals = &opc->suuid;
755         rs.sr_err = syncprov_state_ctrl( &sop, &rs, &e_uuid,
756                 mode, ctrls, 0, 1, &cookie );
757
758         rs.sr_entry = e;
759         rs.sr_ctrls = ctrls;
760         switch( mode ) {
761         case LDAP_SYNC_ADD:
762                 if ( opc->sreference ) {
763                         rs.sr_ref = get_entry_referrals( &sop, e );
764                         send_search_reference( &sop, &rs );
765                         ber_bvarray_free( rs.sr_ref );
766                         break;
767                 }
768                 /* fallthru */
769         case LDAP_SYNC_MODIFY:
770                 rs.sr_attrs = sop.ors_attrs;
771                 send_search_entry( &sop, &rs );
772                 break;
773         case LDAP_SYNC_DELETE:
774                 e_uuid.e_attrs = NULL;
775                 e_uuid.e_name = opc->sdn;
776                 e_uuid.e_nname = opc->sndn;
777                 rs.sr_entry = &e_uuid;
778                 if ( opc->sreference ) {
779                         struct berval bv = BER_BVNULL;
780                         rs.sr_ref = &bv;
781                         send_search_reference( &sop, &rs );
782                 } else {
783                         send_search_entry( &sop, &rs );
784                 }
785                 break;
786         default:
787                 assert(0);
788         }
789         op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
790         rs.sr_ctrls = NULL;
791         return rs.sr_err;
792 }
793
794 static void
795 syncprov_free_syncop( syncops *so )
796 {
797         syncres *sr, *srnext;
798
799         ldap_pvt_thread_mutex_lock( &so->s_mutex );
800         so->s_inuse--;
801         if ( so->s_inuse > 0 ) {
802                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
803                 return;
804         }
805         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
806         filter_free( so->s_op->ors_filter );
807         ch_free( so->s_op );
808         ch_free( so->s_base.bv_val );
809         for ( sr=so->s_res; sr; sr=srnext ) {
810                 srnext = sr->s_next;
811                 ch_free( sr );
812         }
813         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
814         ch_free( so );
815 }
816
817 static int
818 syncprov_drop_psearch( syncops *so )
819 {
820         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
821         so->s_op->o_conn->c_n_ops_executing--;
822         so->s_op->o_conn->c_n_ops_completed++;
823         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
824         syncprov_free_syncop( so );
825 }
826
827 static int
828 syncprov_op_abandon( Operation *op, SlapReply *rs )
829 {
830         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
831         syncprov_info_t         *si = on->on_bi.bi_private;
832         syncops *so, *soprev;
833
834         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
835         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
836                 soprev=so, so=so->s_next ) {
837                 if ( so->s_op->o_connid == op->o_connid &&
838                         so->s_op->o_msgid == op->orn_msgid ) {
839                                 so->s_op->o_abandon = 1;
840                                 soprev->s_next = so->s_next;
841                                 break;
842                 }
843         }
844         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
845         if ( so ) {
846                 /* Is this really a Cancel exop? */
847                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
848                         rs->sr_err = LDAP_CANCELLED;
849                         send_ldap_result( so->s_op, rs );
850                 }
851                 syncprov_drop_psearch( so );
852         }
853         return SLAP_CB_CONTINUE;
854 }
855
856 /* Find which persistent searches are affected by this operation */
857 static void
858 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
859 {
860         slap_overinst *on = opc->son;
861         syncprov_info_t         *si = on->on_bi.bi_private;
862
863         fbase_cookie fc;
864         syncops *ss, *sprev, *snext;
865         Entry *e;
866         Attribute *a;
867         int rc;
868         struct berval newdn;
869         int freefdn = 0;
870
871         fc.fdn = &op->o_req_ndn;
872         /* compute new DN */
873         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
874                 struct berval pdn;
875                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
876                 else dnParent( fc.fdn, &pdn );
877                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
878                 fc.fdn = &newdn;
879                 freefdn = 1;
880         }
881         if ( op->o_tag != LDAP_REQ_ADD ) {
882                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
883                 rc = be_entry_get_rw( op, fc.fdn, NULL, NULL, 0, &e );
884                 op->o_bd->bd_info = (BackendInfo *)on;
885                 if ( rc ) return;
886         } else {
887                 e = op->ora_e;
888         }
889
890         /* Never replicate these */
891         if ( is_entry_syncConsumerSubentry( e )) {
892                 goto done;
893         }
894         if ( saveit ) {
895                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
896                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
897                 opc->sreference = is_entry_referral( e );
898         }
899         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
900                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
901                 if ( a )
902                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
903         }
904
905         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
906         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
907                 sprev = ss, ss=snext)
908         {
909                 syncmatches *sm;
910                 int found = 0;
911
912                 snext = ss->s_next;
913                 /* validate base */
914                 fc.fss = ss;
915                 fc.fbase = 0;
916                 fc.fscope = 0;
917
918                 /* If the base of the search is missing, signal a refresh */
919                 rc = syncprov_findbase( op, &fc );
920                 if ( rc != LDAP_SUCCESS ) {
921                         SlapReply rs = {REP_RESULT};
922                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
923                                 "search base has changed" );
924                         sprev->s_next = snext;
925                         syncprov_drop_psearch( ss );
926                         continue;
927                 }
928
929                 /* If we're sending results now, look for this op in old matches */
930                 if ( !saveit ) {
931                         syncmatches *old;
932                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
933                                 old=sm, sm=sm->sm_next ) {
934                                 if ( sm->sm_op == ss ) {
935                                         found = 1;
936                                         old->sm_next = sm->sm_next;
937                                         op->o_tmpfree( sm, op->o_tmpmemctx );
938                                         break;
939                                 }
940                         }
941                 }
942
943                 /* check if current o_req_dn is in scope and matches filter */
944                 if ( fc.fscope && test_filter( op, e, ss->s_op->ors_filter ) ==
945                         LDAP_COMPARE_TRUE ) {
946                         if ( saveit ) {
947                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
948                                 sm->sm_next = opc->smatches;
949                                 sm->sm_op = ss;
950                                 ss->s_inuse++;
951                                 opc->smatches = sm;
952                         } else {
953                                 /* if found send UPDATE else send ADD */
954                                 syncprov_sendresp( op, opc, ss, e,
955                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD, 1 );
956                         }
957                 } else if ( !saveit && found ) {
958                         /* send DELETE */
959                         syncprov_sendresp( op, opc, ss, NULL, LDAP_SYNC_DELETE, 1 );
960                 }
961         }
962         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
963 done:
964         if ( op->o_tag != LDAP_REQ_ADD ) {
965                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
966                 be_entry_release_r( op, e );
967                 op->o_bd->bd_info = (BackendInfo *)on;
968         }
969         if ( freefdn ) {
970                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
971         }
972 }
973
974 static int
975 syncprov_op_cleanup( Operation *op, SlapReply *rs )
976 {
977         slap_callback *cb = op->o_callback;
978         opcookie *opc = cb->sc_private;
979         slap_overinst *on = opc->son;
980         syncprov_info_t         *si = on->on_bi.bi_private;
981         syncmatches *sm, *snext;
982         modtarget *mt, mtdummy;
983
984         for (sm = opc->smatches; sm; sm=snext) {
985                 snext = sm->sm_next;
986                 syncprov_free_syncop( sm->sm_op );
987                 op->o_tmpfree( sm, op->o_tmpmemctx );
988         }
989
990         /* Remove op from lock table */
991         mtdummy.mt_op = op;
992         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
993         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
994         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
995         if ( mt ) {
996                 modinst *mi = mt->mt_mods;
997
998                 /* If there are more, promote the next one */
999                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1000                 if ( mi->mi_next ) {
1001                         mt->mt_mods = mi->mi_next;
1002                         mt->mt_op = mt->mt_mods->mi_op;
1003                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1004                 } else {
1005                         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1006                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
1007                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1008                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1009                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1010                         ch_free( mt );
1011                 }
1012         }
1013         if ( !BER_BVISNULL( &opc->suuid ))
1014                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1015         if ( !BER_BVISNULL( &opc->sndn ))
1016                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1017         if ( !BER_BVISNULL( &opc->sdn ))
1018                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1019         op->o_callback = cb->sc_next;
1020         op->o_tmpfree(cb, op->o_tmpmemctx);
1021 }
1022
1023 static void
1024 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1025 {
1026         syncprov_info_t         *si = on->on_bi.bi_private;
1027         Modifications mod;
1028         Operation opm;
1029         struct berval bv[2];
1030         BackendInfo *orig;
1031         slap_callback cb = {0};
1032
1033         mod.sml_values = bv;
1034         bv[1].bv_val = NULL;
1035         bv[0] = si->si_ctxcsn;
1036         mod.sml_nvalues = NULL;
1037         mod.sml_desc = slap_schema.si_ad_contextCSN;
1038         mod.sml_op = LDAP_MOD_REPLACE;
1039         mod.sml_next = NULL;
1040
1041         cb.sc_response = slap_null_cb;
1042         opm = *op;
1043         opm.o_tag = LDAP_REQ_MODIFY;
1044         opm.o_callback = &cb;
1045         opm.orm_modlist = &mod;
1046         opm.o_req_dn = op->o_bd->be_suffix[0];
1047         opm.o_req_ndn = op->o_bd->be_nsuffix[0];
1048         orig = opm.o_bd->bd_info;
1049         opm.o_bd->bd_info = on->on_info->oi_orig;
1050         opm.o_bd->be_modify( &opm, rs );
1051 }
1052
1053 static int
1054 syncprov_op_response( Operation *op, SlapReply *rs )
1055 {
1056         opcookie *opc = op->o_callback->sc_private;
1057         slap_overinst *on = opc->son;
1058         syncprov_info_t         *si = on->on_bi.bi_private;
1059         syncmatches *sm;
1060
1061         if ( rs->sr_err == LDAP_SUCCESS )
1062         {
1063                 struct berval maxcsn;
1064                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1065
1066                 /* Update our context CSN */
1067                 cbuf[0] = '\0';
1068                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1069                 slap_get_commit_csn( op, &maxcsn );
1070                 if ( !BER_BVISNULL( &maxcsn ) ) {
1071                         strcpy( cbuf, maxcsn.bv_val );
1072                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn ) > 0 ) {
1073                                 strcpy( si->si_ctxcsnbuf, cbuf );
1074                                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
1075                         }
1076                 }
1077
1078                 si->si_numops++;
1079                 if ( si->si_chkops || si->si_chktime ) {
1080                         int do_check=0;
1081                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1082                                 do_check = 1;
1083                                 si->si_numops = 0;
1084                         }
1085                         if ( si->si_chktime &&
1086                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1087                                 do_check = 1;
1088                                 si->si_chklast = op->o_time;
1089                         }
1090                         if ( do_check ) {
1091                                 syncprov_checkpoint( op, rs, on );
1092                         }
1093                 }
1094                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1095
1096                 opc->sctxcsn.bv_len = maxcsn.bv_len;
1097                 opc->sctxcsn.bv_val = cbuf;
1098
1099                 /* Handle any persistent searches */
1100                 if ( si->si_ops ) {
1101                         switch(op->o_tag) {
1102                         case LDAP_REQ_ADD:
1103                         case LDAP_REQ_MODIFY:
1104                         case LDAP_REQ_MODRDN:
1105                         case LDAP_REQ_EXTENDED:
1106                                 syncprov_matchops( op, opc, 0 );
1107                                 break;
1108                         case LDAP_REQ_DELETE:
1109                                 /* for each match in opc->smatches:
1110                                  *   send DELETE msg
1111                                  */
1112                                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1113                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1114                                         if ( sm->sm_op->s_op->o_abandon )
1115                                                 continue;
1116                                         syncprov_sendresp( op, opc, sm->sm_op, NULL,
1117                                                 LDAP_SYNC_DELETE, 1 );
1118                                 }
1119                                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1120                                 break;
1121                         }
1122                 }
1123
1124         }
1125         return SLAP_CB_CONTINUE;
1126 }
1127
1128 /* We don't use a subentry to store the context CSN any more.
1129  * We expose the current context CSN as an operational attribute
1130  * of the suffix entry.
1131  */
1132 static int
1133 syncprov_op_compare( Operation *op, SlapReply *rs )
1134 {
1135         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1136         syncprov_info_t         *si = on->on_bi.bi_private;
1137         int rc = SLAP_CB_CONTINUE;
1138
1139         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1140                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1141         {
1142                 Entry e = {0};
1143                 Attribute a = {0};
1144                 struct berval bv[2];
1145
1146                 e.e_name = op->o_bd->be_suffix[0];
1147                 e.e_nname = op->o_bd->be_nsuffix[0];
1148
1149                 BER_BVZERO( &bv[1] );
1150                 bv[0] = si->si_ctxcsn;
1151
1152                 a.a_desc = slap_schema.si_ad_contextCSN;
1153                 a.a_vals = bv;
1154                 a.a_nvals = a.a_vals;
1155
1156                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1157
1158                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1159                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1160                 if ( ! rs->sr_err ) {
1161                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1162                         goto return_results;
1163                 }
1164
1165                 if ( get_assert( op ) &&
1166                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1167                 {
1168                         rs->sr_err = LDAP_ASSERTION_FAILED;
1169                         goto return_results;
1170                 }
1171
1172
1173                 rs->sr_err = LDAP_COMPARE_FALSE;
1174
1175                 if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
1176                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1177                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1178                                 a.a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
1179                 {
1180                         rs->sr_err = LDAP_COMPARE_TRUE;
1181                 }
1182
1183 return_results:;
1184
1185                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1186
1187                 send_ldap_result( op, rs );
1188
1189                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1190                         rs->sr_err = LDAP_SUCCESS;
1191                 }
1192                 rc = rs->sr_err;
1193         }
1194
1195         return rc;
1196 }
1197
1198 static int
1199 syncprov_op_mod( Operation *op, SlapReply *rs )
1200 {
1201         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1202         syncprov_info_t         *si = on->on_bi.bi_private;
1203
1204         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+
1205                 sizeof(opcookie) +
1206                 (si->si_ops ? sizeof(modinst) : 0 ),
1207                 op->o_tmpmemctx);
1208         opcookie *opc = (opcookie *)(cb+1);
1209         opc->son = on;
1210         cb->sc_response = syncprov_op_response;
1211         cb->sc_cleanup = syncprov_op_cleanup;
1212         cb->sc_private = opc;
1213         cb->sc_next = op->o_callback;
1214         op->o_callback = cb;
1215
1216         /* If there are active persistent searches, lock this operation.
1217          * See seqmod.c for the locking logic on its own.
1218          */
1219         if ( si->si_ops ) {
1220                 modtarget *mt, mtdummy;
1221                 modinst *mi;
1222
1223                 mi = (modinst *)(opc+1);
1224                 mi->mi_op = op;
1225
1226                 /* See if we're already modifying this entry... */
1227                 mtdummy.mt_op = op;
1228                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1229                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1230                 if ( mt ) {
1231                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1232                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1233                         mt->mt_tail->mi_next = mi;
1234                         mt->mt_tail = mi;
1235                         /* wait for this op to get to head of list */
1236                         while ( mt->mt_mods != mi ) {
1237                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1238                                 ldap_pvt_thread_yield();
1239                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1240                         }
1241                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1242                 } else {
1243                         /* Record that we're modifying this entry now */
1244                         mt = ch_malloc( sizeof(modtarget) );
1245                         mt->mt_mods = mi;
1246                         mt->mt_tail = mi;
1247                         mt->mt_op = mi->mi_op;
1248                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1249                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1250                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1251                 }
1252
1253                 if ( op->o_tag != LDAP_REQ_ADD )
1254                         syncprov_matchops( op, opc, 1 );
1255         }
1256
1257         return SLAP_CB_CONTINUE;
1258 }
1259
1260 static int
1261 syncprov_op_extended( Operation *op, SlapReply *rs )
1262 {
1263         if ( exop_is_write( op ))
1264                 return syncprov_op_mod( op, rs );
1265
1266         return SLAP_CB_CONTINUE;
1267 }
1268
1269 typedef struct searchstate {
1270         slap_overinst *ss_on;
1271         syncops *ss_so;
1272 } searchstate;
1273
1274 static int
1275 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1276 {
1277         if ( rs->sr_ctrls ) {
1278                 op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
1279                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1280                 rs->sr_ctrls = NULL;
1281         }
1282         return 0;
1283 }
1284
1285 static void
1286 syncprov_detach_op( Operation *op, syncops *so )
1287 {
1288         Operation *op2;
1289         int i, alen = 0;
1290         size_t size;
1291         char *ptr;
1292
1293         /* count the search attrs */
1294         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1295                 alen += op->ors_attrs[i].an_name.bv_len + 1;
1296         }
1297         /* Make a new copy of the operation */
1298         size = sizeof(Operation) + sizeof(Opheader) +
1299                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
1300                 op->o_req_dn.bv_len + 1 +
1301                 op->o_req_ndn.bv_len + 1 +
1302                 op->o_ndn.bv_len + 1 +
1303                 so->s_filterstr.bv_len + 1;
1304         op2 = (Operation *)ch_malloc( size );
1305         *op2 = *op;
1306         op2->o_hdr = (Opheader *)(op2+1);
1307         *op2->o_hdr = *op->o_hdr;
1308         if ( i ) {
1309                 op2->ors_attrs = (AttributeName *)(op2->o_hdr + 1);
1310                 ptr = (char *)(op2->ors_attrs+i+1);
1311                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1312                         op2->ors_attrs[i] = op->ors_attrs[i];
1313                         op2->ors_attrs[i].an_name.bv_val = ptr;
1314                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
1315                 }
1316                 BER_BVZERO( &op2->ors_attrs[i].an_name );
1317         } else {
1318                 ptr = (char *)(op2->o_hdr + 1);
1319         }
1320         op2->o_ndn.bv_val = ptr;
1321         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
1322         op2->o_dn = op2->o_ndn;
1323         op2->o_req_dn.bv_val = ptr;
1324         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
1325         op2->o_req_ndn.bv_val = ptr;
1326         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
1327         op2->ors_filterstr.bv_val = ptr;
1328         strcpy( ptr, so->s_filterstr.bv_val );
1329         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
1330         op2->ors_filter = str2filter( ptr );
1331         op2->o_controls = NULL;
1332         op2->o_callback = NULL;
1333         so->s_op = op2;
1334
1335         /* Increment number of ops so that idletimeout ignores us */
1336         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1337         op->o_conn->c_n_ops_executing++;
1338         op->o_conn->c_n_ops_completed--;
1339         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1340 }
1341
1342 static int
1343 syncprov_search_response( Operation *op, SlapReply *rs )
1344 {
1345         searchstate *ss = op->o_callback->sc_private;
1346         slap_overinst *on = ss->ss_on;
1347         syncprov_info_t         *si = on->on_bi.bi_private;
1348         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
1349
1350         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
1351                 int i;
1352                 /* If we got a referral without a referral object, there's
1353                  * something missing that we cannot replicate. Just ignore it.
1354                  * The consumer will abort because we didn't send the expected
1355                  * control.
1356                  */
1357                 if ( !rs->sr_entry ) {
1358                         assert( rs->sr_entry );
1359                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
1360                         return SLAP_CB_CONTINUE;
1361                 }
1362                 if ( srs->sr_state.ctxcsn ) {
1363                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
1364                                 slap_schema.si_ad_entryCSN );
1365                         /* Don't send the ctx entry twice */
1366                         if ( bvmatch( &a->a_nvals[0], srs->sr_state.ctxcsn ))
1367                                 return LDAP_SUCCESS;
1368                 }
1369                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1370                         op->o_tmpmemctx );
1371                 rs->sr_ctrls[1] = NULL;
1372                 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
1373                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
1374         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
1375                 struct berval cookie;
1376
1377                 slap_compose_sync_cookie( op, &cookie,
1378                         &op->ors_filter->f_and->f_ava->aa_value,
1379                         srs->sr_state.sid, srs->sr_state.rid );
1380
1381                 /* Is this a regular refresh? */
1382                 if ( !ss->ss_so ) {
1383                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1384                                 op->o_tmpmemctx );
1385                         rs->sr_ctrls[1] = NULL;
1386                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
1387                                 0, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
1388                 } else {
1389                         int locked = 0;
1390                 /* It's RefreshAndPersist, transition to Persist phase */
1391                         syncprov_sendinfo( op, rs, rs->sr_nentries ?
1392                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
1393                                 &cookie, 1, NULL, 0 );
1394                         /* Flush any queued persist messages */
1395                         if ( ss->ss_so->s_res ) {
1396                                 syncres *sr, *srnext;
1397                                 Entry *e;
1398                                 opcookie opc;
1399
1400                                 opc.son = on;
1401                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
1402                                 locked = 1;
1403                                 for (sr = ss->ss_so->s_res; sr; sr=srnext) {
1404                                         int rc = LDAP_SUCCESS;
1405                                         srnext = sr->s_next;
1406                                         opc.sdn = sr->s_dn;
1407                                         opc.sndn = sr->s_ndn;
1408                                         opc.suuid = sr->s_uuid;
1409                                         opc.sctxcsn = sr->s_csn;
1410                                         opc.sreference = sr->s_isreference;
1411                                         e = NULL;
1412
1413                                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
1414                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1415                                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
1416                                                 op->o_bd->bd_info = (BackendInfo *)on;
1417                                         }
1418                                         if ( rc == LDAP_SUCCESS )
1419                                                 syncprov_sendresp( op, &opc, ss->ss_so, e,
1420                                                         sr->s_mode, 0 );
1421
1422                                         if ( e ) {
1423                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1424                                                 be_entry_release_r( op, e );
1425                                                 op->o_bd->bd_info = (BackendInfo *)on;
1426                                         }
1427                                         ch_free( sr );
1428                                 }
1429                                 ss->ss_so->s_res = NULL;
1430                                 ss->ss_so->s_restail = NULL;
1431                         }
1432
1433                         /* Turn off the refreshing flag */
1434                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
1435                         if ( locked )
1436                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
1437
1438                         /* Detach this Op from frontend control */
1439                         syncprov_detach_op( op, ss->ss_so );
1440
1441                         return LDAP_SUCCESS;
1442                 }
1443         }
1444
1445         return SLAP_CB_CONTINUE;
1446 }
1447
1448 static int
1449 syncprov_op_search( Operation *op, SlapReply *rs )
1450 {
1451         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1452         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1453         slap_callback   *cb;
1454         int gotstate = 0, nochange = 0;
1455         Filter *fand, *fava;
1456         syncops *sop = NULL;
1457         searchstate *ss;
1458         sync_control *srs;
1459
1460         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
1461
1462         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1463                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
1464                 return rs->sr_err;
1465         }
1466
1467         srs = op->o_controls[slap_cids.sc_LDAPsync];
1468
1469         /* If this is a persistent search, set it up right away */
1470         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
1471                 syncops so = {0};
1472                 fbase_cookie fc;
1473                 opcookie opc;
1474                 slap_callback sc;
1475
1476                 fc.fss = &so;
1477                 fc.fbase = 0;
1478                 so.s_eid = NOID;
1479                 so.s_op = op;
1480                 so.s_flags = PS_IS_REFRESHING;
1481                 /* syncprov_findbase expects to be called as a callback... */
1482                 sc.sc_private = &opc;
1483                 opc.son = on;
1484                 cb = op->o_callback;
1485                 op->o_callback = &sc;
1486                 rs->sr_err = syncprov_findbase( op, &fc );
1487                 op->o_callback = cb;
1488
1489                 if ( rs->sr_err != LDAP_SUCCESS ) {
1490                         send_ldap_result( op, rs );
1491                         return rs->sr_err;
1492                 }
1493                 sop = ch_malloc( sizeof( syncops ));
1494                 *sop = so;
1495                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
1496                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1497                 sop->s_sid = srs->sr_state.sid;
1498                 sop->s_rid = srs->sr_state.rid;
1499                 sop->s_next = si->si_ops;
1500                 sop->s_inuse = 1;
1501                 si->si_ops = sop;
1502                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1503         }
1504
1505         /* If we have a cookie, handle the PRESENT lookups
1506          */
1507         if ( srs->sr_state.ctxcsn ) {
1508                 /* Is the CSN in a valid format? */
1509                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
1510                         send_ldap_error( op, rs, LDAP_OTHER, "invalid sync cookie" );
1511                         return rs->sr_err;
1512                 }
1513                 /* If just Refreshing and nothing has changed, shortcut it */
1514                 if ( bvmatch( srs->sr_state.ctxcsn, &si->si_ctxcsn )) {
1515                         nochange = 1;
1516                         if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
1517                                 LDAPControl     *ctrls[2];
1518
1519                                 ctrls[0] = NULL;
1520                                 ctrls[1] = NULL;
1521                                 syncprov_done_ctrl( op, rs, ctrls, 0, 0,
1522                                         NULL, LDAP_SYNC_REFRESH_DELETES );
1523                                 rs->sr_ctrls = ctrls;
1524                                 rs->sr_err = LDAP_SUCCESS;
1525                                 send_ldap_result( op, rs );
1526                                 rs->sr_ctrls = NULL;
1527                                 return rs->sr_err;
1528                         }
1529                         goto shortcut;
1530                 }
1531                 /* Is the CSN still present in the database? */
1532                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
1533                         /* No, so a reload is required */
1534 #if 0           /* the consumer doesn't seem to send this hint */
1535                         if ( op->o_sync_rhint == 0 ) {
1536                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
1537                                 return rs->sr_err;
1538                         }
1539 #endif
1540                 } else {
1541                         gotstate = 1;
1542                         /* If context has changed, check for Present UUIDs */
1543                         if ( syncprov_findcsn( op, FIND_PRESENT ) != LDAP_SUCCESS ) {
1544                                 send_ldap_result( op, rs );
1545                                 return rs->sr_err;
1546                         }
1547                 }
1548         }
1549
1550         /* Append CSN range to search filter, save original filter
1551          * for persistent search evaluation
1552          */
1553         if ( sop ) {
1554                 sop->s_filterstr= op->ors_filterstr;
1555         }
1556
1557         fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1558         fand->f_choice = LDAP_FILTER_AND;
1559         fand->f_next = NULL;
1560         fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1561         fava->f_choice = LDAP_FILTER_LE;
1562         fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1563         fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1564         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1565         ber_dupbv_x( &fava->f_ava->aa_value, &si->si_ctxcsn, op->o_tmpmemctx );
1566         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1567         fand->f_and = fava;
1568         if ( gotstate ) {
1569                 fava->f_next = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1570                 fava = fava->f_next;
1571                 fava->f_choice = LDAP_FILTER_GE;
1572                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1573                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1574                 ber_dupbv_x( &fava->f_ava->aa_value, srs->sr_state.ctxcsn, op->o_tmpmemctx );
1575         }
1576         fava->f_next = op->ors_filter;
1577         op->ors_filter = fand;
1578         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1579
1580 shortcut:
1581         /* Let our callback add needed info to returned entries */
1582         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1583         ss = (searchstate *)(cb+1);
1584         ss->ss_on = on;
1585         ss->ss_so = sop;
1586         cb->sc_response = syncprov_search_response;
1587         cb->sc_cleanup = syncprov_search_cleanup;
1588         cb->sc_private = ss;
1589         cb->sc_next = op->o_callback;
1590         op->o_callback = cb;
1591
1592 #if 0   /* I don't think we need to shortcircuit back-bdb any more */
1593         op->o_sync_mode &= SLAP_CONTROL_MASK;
1594 #endif
1595
1596         /* If this is a persistent search and no changes were reported during
1597          * the refresh phase, just invoke the response callback to transition
1598          * us into persist phase
1599          */
1600         if ( nochange ) {
1601                 rs->sr_err = LDAP_SUCCESS;
1602                 rs->sr_nentries = 0;
1603                 send_ldap_result( op, rs );
1604                 return rs->sr_err;
1605         }
1606         return SLAP_CB_CONTINUE;
1607 }
1608
1609 static int
1610 syncprov_operational(
1611         Operation *op,
1612         SlapReply *rs )
1613 {
1614         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1615         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1616
1617         if ( rs->sr_entry &&
1618                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
1619
1620                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
1621                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
1622                         Attribute *a, **ap = NULL;
1623
1624                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
1625                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
1626                                         break;
1627                         }
1628
1629                         if ( !a ) {
1630                                 for ( ap = &rs->sr_operational_attrs; *ap; ap=&(*ap)->a_next );
1631
1632                                 a = ch_malloc( sizeof(Attribute));
1633                                 a->a_desc = slap_schema.si_ad_contextCSN;
1634                                 a->a_vals = ch_malloc( 2 * sizeof(struct berval));
1635                                 a->a_vals[1].bv_val = NULL;
1636                                 a->a_nvals = a->a_vals;
1637                                 a->a_next = NULL;
1638                                 a->a_flags = 0;
1639                                 *ap = a;
1640                         }
1641
1642                         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1643                         if ( !ap ) {
1644                                 strcpy( a->a_vals[0].bv_val, si->si_ctxcsnbuf );
1645                         } else {
1646                                 ber_dupbv( &a->a_vals[0], &si->si_ctxcsn );
1647                         }
1648                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1649                 }
1650         }
1651         return SLAP_CB_CONTINUE;
1652 }
1653
1654 static int
1655 syncprov_db_config(
1656         BackendDB       *be,
1657         const char      *fname,
1658         int             lineno,
1659         int             argc,
1660         char    **argv
1661 )
1662 {
1663         slap_overinst           *on = (slap_overinst *)be->bd_info;
1664         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1665
1666         if ( strcasecmp( argv[ 0 ], "syncprov-checkpoint" ) == 0 ) {
1667                 if ( argc != 3 ) {
1668                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1669                                 "\"syncprov-checkpoint <ops> <minutes>\"\n", fname, lineno );
1670                         return -1;
1671                 }
1672                 si->si_chkops = atoi( argv[1] );
1673                 si->si_chktime = atoi( argv[2] ) * 60;
1674                 return 0;
1675
1676         }
1677
1678         return SLAP_CONF_UNKNOWN;
1679 }
1680
1681 /* Cheating - we have no thread pool context for these functions,
1682  * so make one.
1683  */
1684 typedef struct thread_keys {
1685         void *key;
1686         void *data;
1687         ldap_pvt_thread_pool_keyfree_t *xfree;
1688 } thread_keys;
1689
1690 #define MAXKEYS 32
1691 /* A fake thread context */
1692 static thread_keys thrctx[MAXKEYS];
1693
1694 /* Read any existing contextCSN from the underlying db.
1695  * Then search for any entries newer than that. If no value exists,
1696  * just generate it. Cache whatever result.
1697  */
1698 static int
1699 syncprov_db_open(
1700     BackendDB *be
1701 )
1702 {
1703         slap_overinst   *on = (slap_overinst *) be->bd_info;
1704         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1705
1706         Connection conn;
1707         char opbuf[OPERATION_BUFFER_SIZE];
1708         char ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1709         Operation *op = (Operation *)opbuf;
1710         Entry *e;
1711         Attribute *a;
1712         int rc;
1713
1714         connection_fake_init( &conn, op, thrctx );
1715         op->o_bd = be;
1716         op->o_dn = be->be_rootdn;
1717         op->o_ndn = be->be_rootndn;
1718
1719         ctxcsnbuf[0] = '\0';
1720
1721         op->o_bd->bd_info = on->on_info->oi_orig;
1722         rc = be_entry_get_rw( op, be->be_nsuffix, NULL,
1723                 slap_schema.si_ad_contextCSN, 0, &e );
1724
1725         if ( e ) {
1726                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
1727                 if ( a ) {
1728                         si->si_ctxcsn.bv_len = a->a_nvals[0].bv_len;
1729                         if ( si->si_ctxcsn.bv_len >= sizeof(si->si_ctxcsnbuf ))
1730                                 si->si_ctxcsn.bv_len = sizeof(si->si_ctxcsnbuf)-1;
1731                         strncpy( si->si_ctxcsnbuf, a->a_nvals[0].bv_val,
1732                                 si->si_ctxcsn.bv_len );
1733                         si->si_ctxcsnbuf[si->si_ctxcsn.bv_len] = '\0';
1734                         strcpy( ctxcsnbuf, si->si_ctxcsnbuf );
1735                 }
1736                 be_entry_release_r( op, e );
1737                 op->o_bd->bd_info = (BackendInfo *)on;
1738                 op->o_req_dn = be->be_suffix[0];
1739                 op->o_req_ndn = be->be_nsuffix[0];
1740                 op->ors_scope = LDAP_SCOPE_SUBTREE;
1741                 syncprov_findcsn( op, FIND_MAXCSN );
1742         }
1743
1744         if ( BER_BVISEMPTY( &si->si_ctxcsn ) ) {
1745                 slap_get_csn( op, si->si_ctxcsnbuf, sizeof(si->si_ctxcsnbuf),
1746                                 &si->si_ctxcsn, 0 );
1747         }
1748
1749         /* If our ctxcsn is different from what was read from the root
1750          * entry, write the new value out.
1751          */
1752         if ( strcmp( si->si_ctxcsnbuf, ctxcsnbuf )) {
1753                 SlapReply rs = {REP_RESULT};
1754                 syncprov_checkpoint( op, &rs, on );
1755         }
1756
1757         op->o_bd->bd_info = (BackendInfo *)on;
1758         return 0;
1759 }
1760
1761 /* Write the current contextCSN into the underlying db.
1762  */
1763 static int
1764 syncprov_db_close(
1765     BackendDB *be
1766 )
1767 {
1768     slap_overinst   *on = (slap_overinst *) be->bd_info;
1769     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1770         int i;
1771
1772         if ( si->si_numops ) {
1773                 Connection conn;
1774                 char opbuf[OPERATION_BUFFER_SIZE];
1775                 Operation *op = (Operation *)opbuf;
1776                 SlapReply rs = {REP_RESULT};
1777
1778                 connection_fake_init( &conn, op, thrctx );
1779                 op->o_bd = be;
1780                 op->o_dn = be->be_rootdn;
1781                 op->o_ndn = be->be_rootndn;
1782                 syncprov_checkpoint( op, &rs, on );
1783         }
1784         for ( i=0; thrctx[i].key; i++) {
1785                 if ( thrctx[i].xfree )
1786                         thrctx[i].xfree( thrctx[i].key, thrctx[i].data );
1787                 thrctx[i].key = NULL;
1788         }
1789
1790     return 0;
1791 }
1792
1793 static int
1794 syncprov_db_init(
1795         BackendDB *be
1796 )
1797 {
1798         slap_overinst   *on = (slap_overinst *)be->bd_info;
1799         syncprov_info_t *si;
1800
1801         si = ch_calloc(1, sizeof(syncprov_info_t));
1802         on->on_bi.bi_private = si;
1803         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
1804         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
1805         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
1806         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
1807
1808         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
1809         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
1810
1811         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
1812         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1813
1814         return 0;
1815 }
1816
1817 static int
1818 syncprov_db_destroy(
1819         BackendDB *be
1820 )
1821 {
1822         slap_overinst   *on = (slap_overinst *)be->bd_info;
1823         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1824
1825         if ( si ) {
1826                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
1827                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
1828                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
1829                 ch_free( si );
1830         }
1831
1832         return 0;
1833 }
1834
1835 static int syncprov_parseCtrl (
1836         Operation *op,
1837         SlapReply *rs,
1838         LDAPControl *ctrl )
1839 {
1840         ber_tag_t tag;
1841         BerElement *ber;
1842         ber_int_t mode;
1843         ber_len_t len;
1844         struct berval cookie = BER_BVNULL;
1845         sync_control *sr;
1846         int rhint = 0;
1847
1848         if ( op->o_sync != SLAP_CONTROL_NONE ) {
1849                 rs->sr_text = "Sync control specified multiple times";
1850                 return LDAP_PROTOCOL_ERROR;
1851         }
1852
1853         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
1854                 rs->sr_text = "Sync control specified with pagedResults control";
1855                 return LDAP_PROTOCOL_ERROR;
1856         }
1857
1858         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1859                 rs->sr_text = "Sync control value is empty (or absent)";
1860                 return LDAP_PROTOCOL_ERROR;
1861         }
1862
1863         /* Parse the control value
1864          *      syncRequestValue ::= SEQUENCE {
1865          *              mode   ENUMERATED {
1866          *                      -- 0 unused
1867          *                      refreshOnly             (1),
1868          *                      -- 2 reserved
1869          *                      refreshAndPersist       (3)
1870          *              },
1871          *              cookie  syncCookie OPTIONAL
1872          *      }
1873          */
1874
1875         ber = ber_init( &ctrl->ldctl_value );
1876         if( ber == NULL ) {
1877                 rs->sr_text = "internal error";
1878                 return LDAP_OTHER;
1879         }
1880
1881         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
1882                 rs->sr_text = "Sync control : mode decoding error";
1883                 return LDAP_PROTOCOL_ERROR;
1884         }
1885
1886         switch( mode ) {
1887         case LDAP_SYNC_REFRESH_ONLY:
1888                 mode = SLAP_SYNC_REFRESH;
1889                 break;
1890         case LDAP_SYNC_REFRESH_AND_PERSIST:
1891                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
1892                 break;
1893         default:
1894                 rs->sr_text = "Sync control : unknown update mode";
1895                 return LDAP_PROTOCOL_ERROR;
1896         }
1897
1898         tag = ber_peek_tag( ber, &len );
1899
1900         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
1901                 if (( ber_scanf( ber, /*{*/ "o", &cookie )) == LBER_ERROR ) {
1902                         rs->sr_text = "Sync control : cookie decoding error";
1903                         return LDAP_PROTOCOL_ERROR;
1904                 }
1905         }
1906         if ( tag == LDAP_TAG_RELOAD_HINT ) {
1907                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
1908                         rs->sr_text = "Sync control : rhint decoding error";
1909                         return LDAP_PROTOCOL_ERROR;
1910                 }
1911         }
1912         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
1913                         rs->sr_text = "Sync control : decoding error";
1914                         return LDAP_PROTOCOL_ERROR;
1915         }
1916         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
1917         sr->sr_rhint = rhint;
1918         if (!BER_BVISNULL(&cookie)) {
1919                 ber_bvarray_add( &sr->sr_state.octet_str, &cookie );
1920                 slap_parse_sync_cookie( &sr->sr_state );
1921         }
1922
1923         op->o_controls[slap_cids.sc_LDAPsync] = sr;
1924
1925         (void) ber_free( ber, 1 );
1926
1927         op->o_sync = ctrl->ldctl_iscritical
1928                 ? SLAP_CONTROL_CRITICAL
1929                 : SLAP_CONTROL_NONCRITICAL;
1930
1931         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
1932
1933         return LDAP_SUCCESS;
1934 }
1935
1936 /* This overlay is set up for dynamic loading via moduleload. For static
1937  * configuration, you'll need to arrange for the slap_overinst to be
1938  * initialized and registered by some other function inside slapd.
1939  */
1940
1941 static slap_overinst            syncprov;
1942
1943 int
1944 syncprov_init()
1945 {
1946         int rc;
1947
1948         rc = register_supported_control( LDAP_CONTROL_SYNC,
1949                 SLAP_CTRL_HIDE|SLAP_CTRL_SEARCH, NULL,
1950                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
1951         if ( rc != LDAP_SUCCESS ) {
1952                 fprintf( stderr, "Failed to register control %d\n", rc );
1953                 return rc;
1954         }
1955
1956         syncprov.on_bi.bi_type = "syncprov";
1957         syncprov.on_bi.bi_db_init = syncprov_db_init;
1958         syncprov.on_bi.bi_db_config = syncprov_db_config;
1959         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
1960         syncprov.on_bi.bi_db_open = syncprov_db_open;
1961         syncprov.on_bi.bi_db_close = syncprov_db_close;
1962
1963         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
1964         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
1965
1966         syncprov.on_bi.bi_op_add = syncprov_op_mod;
1967         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
1968         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
1969         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
1970         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
1971         syncprov.on_bi.bi_op_search = syncprov_op_search;
1972         syncprov.on_bi.bi_extended = syncprov_op_extended;
1973         syncprov.on_bi.bi_operational = syncprov_operational;
1974
1975         return overlay_register( &syncprov );
1976 }
1977
1978 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
1979 int
1980 init_module( int argc, char *argv[] )
1981 {
1982         return syncprov_init();
1983 }
1984 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
1985
1986 #endif /* defined(SLAPD_OVER_SYNCPROV) */