]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
edceb1bf1a07903d3473f0f35b3d4b94a50321bb
[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 typedef struct fpres_cookie {
530         int num;
531         BerVarray uuids;
532 } fpres_cookie;
533
534 static int
535 findpres_cb( Operation *op, SlapReply *rs )
536 {
537         slap_callback *sc = op->o_callback;
538         fpres_cookie *pc = sc->sc_private;
539         int ret = SLAP_CB_CONTINUE;
540
541         if ( rs->sr_type == REP_SEARCH ) {
542                 ret = slap_build_syncUUID_set( op, &pc->uuids, rs->sr_entry );
543                 if ( ret > 0 ) {
544                         pc->num++;
545                         ret = LDAP_SUCCESS;
546                         if ( pc->num == SLAP_SYNCUUID_SET_SIZE ) {
547                                 ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
548                                         0, pc->uuids, 0 );
549                                 ber_bvarray_free_x( pc->uuids, op->o_tmpmemctx );
550                                 pc->uuids = NULL;
551                                 pc->num = 0;
552                         }
553                 } else {
554                         ret = LDAP_OTHER;
555                 }
556         } else if ( rs->sr_type == REP_RESULT ) {
557                 ret = rs->sr_err;
558                 if ( pc->num ) {
559                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
560                                 0, pc->uuids, 0 );
561                         ber_bvarray_free_x( pc->uuids, op->o_tmpmemctx );
562                         pc->uuids = NULL;
563                         pc->num = 0;
564                 }
565         }
566         return ret;
567 }
568
569
570 static int
571 syncprov_findcsn( Operation *op, int mode )
572 {
573         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
574         syncprov_info_t         *si = on->on_bi.bi_private;
575
576         slap_callback cb = {0};
577         Operation fop;
578         SlapReply frs = { REP_RESULT };
579         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
580         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
581         struct berval fbuf, maxcsn;
582         Filter cf;
583         AttributeAssertion eq;
584         int rc = LDAP_SUCCESS;
585         fpres_cookie pcookie;
586         int locked = 0;
587         sync_control *srs;
588
589         if ( mode != FIND_MAXCSN ) {
590                 srs = op->o_controls[slap_cids.sc_LDAPsync];
591
592                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
593                         return LDAP_OTHER;
594                 }
595         }
596
597         fop = *op;
598         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
599
600         fbuf.bv_val = buf;
601         cf.f_ava = &eq;
602         cf.f_av_desc = slap_schema.si_ad_entryCSN;
603         cf.f_next = NULL;
604
605         switch( mode ) {
606         case FIND_MAXCSN:
607                 cf.f_choice = LDAP_FILTER_GE;
608                 cf.f_av_value = si->si_ctxcsn;
609                 fbuf.bv_len = sprintf( buf, "(entryCSN>=%s)",
610                         cf.f_av_value.bv_val );
611                 fop.ors_attrsonly = 0;
612                 fop.ors_attrs = csn_anlist;
613                 fop.ors_slimit = SLAP_NO_LIMIT;
614                 cb.sc_private = &maxcsn;
615                 cb.sc_response = findmax_cb;
616                 maxcsn.bv_val = cbuf;
617                 maxcsn.bv_len = 0;
618                 break;
619         case FIND_CSN:
620                 cf.f_choice = LDAP_FILTER_LE;
621                 cf.f_av_value = *srs->sr_state.ctxcsn;
622                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)",
623                         cf.f_av_value.bv_val );
624                 fop.ors_attrsonly = 1;
625                 fop.ors_attrs = slap_anlist_no_attrs;
626                 fop.ors_slimit = 1;
627                 cb.sc_private = NULL;
628                 cb.sc_response = findcsn_cb;
629                 break;
630         case FIND_PRESENT:
631                 cf.f_choice = LDAP_FILTER_LE;
632                 cf.f_av_value = *srs->sr_state.ctxcsn;
633                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)",
634                         cf.f_av_value.bv_val );
635                 fop.ors_attrsonly = 0;
636                 fop.ors_attrs = uuid_anlist;
637                 fop.ors_slimit = SLAP_NO_LIMIT;
638                 /* We want pure entries, not referrals */
639                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
640                 cb.sc_private = &pcookie;
641                 cb.sc_response = findpres_cb;
642                 pcookie.num = 0;
643                 pcookie.uuids = NULL;
644                 break;
645         }
646         fop.o_callback = &cb;
647         fop.ors_limit = NULL;
648         fop.ors_tlimit = SLAP_NO_LIMIT;
649         fop.ors_filter = &cf;
650         fop.ors_filterstr = fbuf;
651
652         fop.o_bd->bd_info = on->on_info->oi_orig;
653         fop.o_bd->be_search( &fop, &frs );
654         fop.o_bd->bd_info = (BackendInfo *)on;
655
656         switch( mode ) {
657         case FIND_MAXCSN:
658                 if ( maxcsn.bv_len ) {
659                         strcpy( si->si_ctxcsnbuf, maxcsn.bv_val );
660                         si->si_ctxcsn.bv_len = maxcsn.bv_len;
661                 }
662                 break;
663         case FIND_CSN:
664                 /* If matching CSN was not found, invalidate the context. */
665                 if ( !cb.sc_private ) rc = LDAP_NO_SUCH_OBJECT;
666                 break;
667         case FIND_PRESENT:
668                 break;
669         }
670
671         return rc;
672 }
673
674 /* Queue a persistent search response if still in Refresh stage */
675 static int
676 syncprov_qresp( opcookie *opc, syncops *so, int mode )
677 {
678         syncres *sr;
679
680         sr = ch_malloc(sizeof(syncres) + opc->suuid.bv_len + 1 +
681                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1 + opc->sctxcsn.bv_len + 1 );
682         sr->s_next = NULL;
683         sr->s_dn.bv_val = (char *)(sr + 1);
684         sr->s_mode = mode;
685         sr->s_isreference = opc->sreference;
686         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val, opc->sdn.bv_val );
687         *(sr->s_ndn.bv_val++) = '\0';
688         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val, opc->sndn.bv_val );
689         *(sr->s_uuid.bv_val++) = '\0';
690         sr->s_csn.bv_val = lutil_strcopy( sr->s_uuid.bv_val, opc->suuid.bv_val );
691
692         if ( !so->s_res ) {
693                 so->s_res = sr;
694         } else {
695                 so->s_restail->s_next = sr;
696         }
697         so->s_restail = sr;
698         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
699         return LDAP_SUCCESS;
700 }
701
702 /* Send a persistent search response */
703 static int
704 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, Entry *e, int mode, int queue )
705 {
706         slap_overinst *on = opc->son;
707         syncprov_info_t *si = on->on_bi.bi_private;
708
709         SlapReply rs = { REP_SEARCH };
710         LDAPControl *ctrls[2];
711         struct berval cookie;
712         Entry e_uuid = {0};
713         Attribute a_uuid = {0};
714         Operation sop = *so->s_op;
715         Opheader ohdr;
716
717         ohdr = *sop.o_hdr;
718         sop.o_hdr = &ohdr;
719         sop.o_tmpmemctx = op->o_tmpmemctx;
720         sop.o_bd = op->o_bd;
721         sop.o_controls = op->o_controls;
722
723         if ( queue && (so->s_flags & PS_IS_REFRESHING) ) {
724                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
725                 if ( so->s_flags & PS_IS_REFRESHING )
726                         return syncprov_qresp( opc, so, mode );
727                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
728         }
729
730         ctrls[1] = NULL;
731         slap_compose_sync_cookie( op, &cookie, &opc->sctxcsn,
732                 so->s_sid, so->s_rid );
733
734         e_uuid.e_attrs = &a_uuid;
735         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
736         a_uuid.a_nvals = &opc->suuid;
737         rs.sr_err = syncprov_state_ctrl( &sop, &rs, &e_uuid,
738                 mode, ctrls, 0, 1, &cookie );
739
740         rs.sr_entry = e;
741         rs.sr_ctrls = ctrls;
742         switch( mode ) {
743         case LDAP_SYNC_ADD:
744                 if ( opc->sreference ) {
745                         rs.sr_ref = get_entry_referrals( &sop, e );
746                         send_search_reference( &sop, &rs );
747                         ber_bvarray_free( rs.sr_ref );
748                         break;
749                 }
750                 /* fallthru */
751         case LDAP_SYNC_MODIFY:
752                 rs.sr_attrs = sop.ors_attrs;
753                 send_search_entry( &sop, &rs );
754                 break;
755         case LDAP_SYNC_DELETE:
756                 e_uuid.e_attrs = NULL;
757                 e_uuid.e_name = opc->sdn;
758                 e_uuid.e_nname = opc->sndn;
759                 rs.sr_entry = &e_uuid;
760                 if ( opc->sreference ) {
761                         struct berval bv = BER_BVNULL;
762                         rs.sr_ref = &bv;
763                         send_search_reference( &sop, &rs );
764                 } else {
765                         send_search_entry( &sop, &rs );
766                 }
767                 break;
768         default:
769                 assert(0);
770         }
771         op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
772         rs.sr_ctrls = NULL;
773         return rs.sr_err;
774 }
775
776 static void
777 syncprov_free_syncop( syncops *so )
778 {
779         syncres *sr, *srnext;
780
781         ldap_pvt_thread_mutex_lock( &so->s_mutex );
782         so->s_inuse--;
783         if ( so->s_inuse > 0 ) {
784                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
785                 return;
786         }
787         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
788         filter_free( so->s_op->ors_filter );
789         ch_free( so->s_op );
790         ch_free( so->s_base.bv_val );
791         for ( sr=so->s_res; sr; sr=srnext ) {
792                 srnext = sr->s_next;
793                 ch_free( sr );
794         }
795         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
796         ch_free( so );
797 }
798
799 static int
800 syncprov_drop_psearch( syncops *so )
801 {
802         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
803         so->s_op->o_conn->c_n_ops_executing--;
804         so->s_op->o_conn->c_n_ops_completed++;
805         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
806         syncprov_free_syncop( so );
807 }
808
809 static int
810 syncprov_op_abandon( Operation *op, SlapReply *rs )
811 {
812         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
813         syncprov_info_t         *si = on->on_bi.bi_private;
814         syncops *so, *soprev;
815
816         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
817         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
818                 soprev=so, so=so->s_next ) {
819                 if ( so->s_op->o_connid == op->o_connid &&
820                         so->s_op->o_msgid == op->orn_msgid ) {
821                                 so->s_op->o_abandon = 1;
822                                 soprev->s_next = so->s_next;
823                                 break;
824                 }
825         }
826         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
827         if ( so ) {
828                 /* Is this really a Cancel exop? */
829                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
830                         rs->sr_err = LDAP_CANCELLED;
831                         send_ldap_result( so->s_op, rs );
832                 }
833                 syncprov_drop_psearch( so );
834         }
835         return SLAP_CB_CONTINUE;
836 }
837
838 /* Find which persistent searches are affected by this operation */
839 static void
840 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
841 {
842         slap_overinst *on = opc->son;
843         syncprov_info_t         *si = on->on_bi.bi_private;
844
845         fbase_cookie fc;
846         syncops *ss, *sprev, *snext;
847         Entry *e;
848         Attribute *a;
849         int rc;
850         struct berval newdn;
851         int freefdn = 0;
852
853         fc.fdn = &op->o_req_ndn;
854         /* compute new DN */
855         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
856                 struct berval pdn;
857                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
858                 else dnParent( fc.fdn, &pdn );
859                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
860                 fc.fdn = &newdn;
861                 freefdn = 1;
862         }
863         if ( op->o_tag != LDAP_REQ_ADD ) {
864                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
865                 rc = be_entry_get_rw( op, fc.fdn, NULL, NULL, 0, &e );
866                 op->o_bd->bd_info = (BackendInfo *)on;
867                 if ( rc ) return;
868         } else {
869                 e = op->ora_e;
870         }
871
872         /* Never replicate these */
873         if ( is_entry_syncConsumerSubentry( e )) {
874                 goto done;
875         }
876         if ( saveit ) {
877                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
878                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
879                 opc->sreference = is_entry_referral( e );
880         }
881         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
882                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
883                 if ( a )
884                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
885         }
886
887         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
888         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
889                 sprev = ss, ss=snext)
890         {
891                 syncmatches *sm;
892                 int found = 0;
893
894                 snext = ss->s_next;
895                 /* validate base */
896                 fc.fss = ss;
897                 fc.fbase = 0;
898                 fc.fscope = 0;
899
900                 /* If the base of the search is missing, signal a refresh */
901                 rc = syncprov_findbase( op, &fc );
902                 if ( rc != LDAP_SUCCESS ) {
903                         SlapReply rs = {REP_RESULT};
904                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
905                                 "search base has changed" );
906                         sprev->s_next = snext;
907                         syncprov_drop_psearch( ss );
908                         continue;
909                 }
910
911                 /* If we're sending results now, look for this op in old matches */
912                 if ( !saveit ) {
913                         syncmatches *old;
914                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
915                                 old=sm, sm=sm->sm_next ) {
916                                 if ( sm->sm_op == ss ) {
917                                         found = 1;
918                                         old->sm_next = sm->sm_next;
919                                         op->o_tmpfree( sm, op->o_tmpmemctx );
920                                         break;
921                                 }
922                         }
923                 }
924
925                 /* check if current o_req_dn is in scope and matches filter */
926                 if ( fc.fscope && test_filter( op, e, ss->s_op->ors_filter ) ==
927                         LDAP_COMPARE_TRUE ) {
928                         if ( saveit ) {
929                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
930                                 sm->sm_next = opc->smatches;
931                                 sm->sm_op = ss;
932                                 ss->s_inuse++;
933                                 opc->smatches = sm;
934                         } else {
935                                 /* if found send UPDATE else send ADD */
936                                 syncprov_sendresp( op, opc, ss, e,
937                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD, 1 );
938                         }
939                 } else if ( !saveit && found ) {
940                         /* send DELETE */
941                         syncprov_sendresp( op, opc, ss, NULL, LDAP_SYNC_DELETE, 1 );
942                 }
943         }
944         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
945 done:
946         if ( op->o_tag != LDAP_REQ_ADD ) {
947                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
948                 be_entry_release_r( op, e );
949                 op->o_bd->bd_info = (BackendInfo *)on;
950         }
951         if ( freefdn ) {
952                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
953         }
954 }
955
956 static int
957 syncprov_op_cleanup( Operation *op, SlapReply *rs )
958 {
959         slap_callback *cb = op->o_callback;
960         opcookie *opc = cb->sc_private;
961         slap_overinst *on = opc->son;
962         syncprov_info_t         *si = on->on_bi.bi_private;
963         syncmatches *sm, *snext;
964         modtarget *mt, mtdummy;
965
966         for (sm = opc->smatches; sm; sm=snext) {
967                 snext = sm->sm_next;
968                 syncprov_free_syncop( sm->sm_op );
969                 op->o_tmpfree( sm, op->o_tmpmemctx );
970         }
971
972         /* Remove op from lock table */
973         mtdummy.mt_op = op;
974         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
975         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
976         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
977         if ( mt ) {
978                 modinst *mi = mt->mt_mods;
979
980                 /* If there are more, promote the next one */
981                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
982                 if ( mi->mi_next ) {
983                         mt->mt_mods = mi->mi_next;
984                         mt->mt_op = mt->mt_mods->mi_op;
985                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
986                 } else {
987                         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
988                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
989                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
990                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
991                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
992                         ch_free( mt );
993                 }
994         }
995         if ( !BER_BVISNULL( &opc->suuid ))
996                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
997         if ( !BER_BVISNULL( &opc->sndn ))
998                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
999         if ( !BER_BVISNULL( &opc->sdn ))
1000                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1001         op->o_callback = cb->sc_next;
1002         op->o_tmpfree(cb, op->o_tmpmemctx);
1003 }
1004
1005 static void
1006 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1007 {
1008         syncprov_info_t         *si = on->on_bi.bi_private;
1009         Modifications mod;
1010         Operation opm;
1011         struct berval bv[2];
1012         BackendInfo *orig;
1013         slap_callback cb = {0};
1014
1015         mod.sml_values = bv;
1016         bv[1].bv_val = NULL;
1017         bv[0] = si->si_ctxcsn;
1018         mod.sml_nvalues = NULL;
1019         mod.sml_desc = slap_schema.si_ad_contextCSN;
1020         mod.sml_op = LDAP_MOD_REPLACE;
1021         mod.sml_next = NULL;
1022
1023         cb.sc_response = slap_null_cb;
1024         opm = *op;
1025         opm.o_tag = LDAP_REQ_MODIFY;
1026         opm.o_callback = &cb;
1027         opm.orm_modlist = &mod;
1028         opm.o_req_dn = op->o_bd->be_suffix[0];
1029         opm.o_req_ndn = op->o_bd->be_nsuffix[0];
1030         orig = opm.o_bd->bd_info;
1031         opm.o_bd->bd_info = on->on_info->oi_orig;
1032         opm.o_bd->be_modify( &opm, rs );
1033 }
1034
1035 static int
1036 syncprov_op_response( Operation *op, SlapReply *rs )
1037 {
1038         opcookie *opc = op->o_callback->sc_private;
1039         slap_overinst *on = opc->son;
1040         syncprov_info_t         *si = on->on_bi.bi_private;
1041         syncmatches *sm;
1042
1043         if ( rs->sr_err == LDAP_SUCCESS )
1044         {
1045                 struct berval maxcsn;
1046                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1047
1048                 /* Update our context CSN */
1049                 cbuf[0] = '\0';
1050                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1051                 slap_get_commit_csn( op, &maxcsn );
1052                 if ( !BER_BVISNULL( &maxcsn ) ) {
1053                         strcpy( cbuf, maxcsn.bv_val );
1054                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn ) > 0 ) {
1055                                 strcpy( si->si_ctxcsnbuf, cbuf );
1056                                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
1057                         }
1058                 }
1059
1060                 si->si_numops++;
1061                 if ( si->si_chkops || si->si_chktime ) {
1062                         int do_check=0;
1063                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1064                                 do_check = 1;
1065                                 si->si_numops = 0;
1066                         }
1067                         if ( si->si_chktime &&
1068                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1069                                 do_check = 1;
1070                                 si->si_chklast = op->o_time;
1071                         }
1072                         if ( do_check ) {
1073                                 syncprov_checkpoint( op, rs, on );
1074                         }
1075                 }
1076                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1077
1078                 opc->sctxcsn.bv_len = maxcsn.bv_len;
1079                 opc->sctxcsn.bv_val = cbuf;
1080
1081                 /* Handle any persistent searches */
1082                 if ( si->si_ops ) {
1083                         switch(op->o_tag) {
1084                         case LDAP_REQ_ADD:
1085                         case LDAP_REQ_MODIFY:
1086                         case LDAP_REQ_MODRDN:
1087                         case LDAP_REQ_EXTENDED:
1088                                 syncprov_matchops( op, opc, 0 );
1089                                 break;
1090                         case LDAP_REQ_DELETE:
1091                                 /* for each match in opc->smatches:
1092                                  *   send DELETE msg
1093                                  */
1094                                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1095                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1096                                         if ( sm->sm_op->s_op->o_abandon )
1097                                                 continue;
1098                                         syncprov_sendresp( op, opc, sm->sm_op, NULL,
1099                                                 LDAP_SYNC_DELETE, 1 );
1100                                 }
1101                                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1102                                 break;
1103                         }
1104                 }
1105
1106         }
1107         return SLAP_CB_CONTINUE;
1108 }
1109
1110 /* We don't use a subentry to store the context CSN any more.
1111  * We expose the current context CSN as an operational attribute
1112  * of the suffix entry.
1113  */
1114 static int
1115 syncprov_op_compare( Operation *op, SlapReply *rs )
1116 {
1117         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1118         syncprov_info_t         *si = on->on_bi.bi_private;
1119         int rc = SLAP_CB_CONTINUE;
1120
1121         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1122                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1123         {
1124                 Entry e = {0};
1125                 Attribute a = {0};
1126                 struct berval bv[2];
1127
1128                 e.e_name = op->o_bd->be_suffix[0];
1129                 e.e_nname = op->o_bd->be_nsuffix[0];
1130
1131                 BER_BVZERO( &bv[1] );
1132                 bv[0] = si->si_ctxcsn;
1133
1134                 a.a_desc = slap_schema.si_ad_contextCSN;
1135                 a.a_vals = bv;
1136                 a.a_nvals = a.a_vals;
1137
1138                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1139
1140                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1141                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1142                 if ( ! rs->sr_err ) {
1143                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1144                         goto return_results;
1145                 }
1146
1147                 if ( get_assert( op ) &&
1148                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1149                 {
1150                         rs->sr_err = LDAP_ASSERTION_FAILED;
1151                         goto return_results;
1152                 }
1153
1154
1155                 rs->sr_err = LDAP_COMPARE_FALSE;
1156
1157                 if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
1158                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1159                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1160                                 a.a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
1161                 {
1162                         rs->sr_err = LDAP_COMPARE_TRUE;
1163                 }
1164
1165 return_results:;
1166
1167                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1168
1169                 send_ldap_result( op, rs );
1170
1171                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1172                         rs->sr_err = LDAP_SUCCESS;
1173                 }
1174                 rc = rs->sr_err;
1175         }
1176
1177         return rc;
1178 }
1179
1180 static int
1181 syncprov_op_mod( Operation *op, SlapReply *rs )
1182 {
1183         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1184         syncprov_info_t         *si = on->on_bi.bi_private;
1185
1186         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+
1187                 sizeof(opcookie) +
1188                 (si->si_ops ? sizeof(modinst) : 0 ),
1189                 op->o_tmpmemctx);
1190         opcookie *opc = (opcookie *)(cb+1);
1191         opc->son = on;
1192         cb->sc_response = syncprov_op_response;
1193         cb->sc_cleanup = syncprov_op_cleanup;
1194         cb->sc_private = opc;
1195         cb->sc_next = op->o_callback;
1196         op->o_callback = cb;
1197
1198         /* If there are active persistent searches, lock this operation.
1199          * See seqmod.c for the locking logic on its own.
1200          */
1201         if ( si->si_ops ) {
1202                 modtarget *mt, mtdummy;
1203                 modinst *mi;
1204
1205                 mi = (modinst *)(opc+1);
1206                 mi->mi_op = op;
1207
1208                 /* See if we're already modifying this entry... */
1209                 mtdummy.mt_op = op;
1210                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1211                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1212                 if ( mt ) {
1213                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1214                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1215                         mt->mt_tail->mi_next = mi;
1216                         mt->mt_tail = mi;
1217                         /* wait for this op to get to head of list */
1218                         while ( mt->mt_mods != mi ) {
1219                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1220                                 ldap_pvt_thread_yield();
1221                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1222                         }
1223                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1224                 } else {
1225                         /* Record that we're modifying this entry now */
1226                         mt = ch_malloc( sizeof(modtarget) );
1227                         mt->mt_mods = mi;
1228                         mt->mt_tail = mi;
1229                         mt->mt_op = mi->mi_op;
1230                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1231                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1232                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1233                 }
1234
1235                 if ( op->o_tag != LDAP_REQ_ADD )
1236                         syncprov_matchops( op, opc, 1 );
1237         }
1238
1239         return SLAP_CB_CONTINUE;
1240 }
1241
1242 static int
1243 syncprov_op_extended( Operation *op, SlapReply *rs )
1244 {
1245         if ( exop_is_write( op ))
1246                 return syncprov_op_mod( op, rs );
1247
1248         return SLAP_CB_CONTINUE;
1249 }
1250
1251 typedef struct searchstate {
1252         slap_overinst *ss_on;
1253         syncops *ss_so;
1254 } searchstate;
1255
1256 static int
1257 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1258 {
1259 #if 0
1260         if ( rs->sr_ctrls ) {
1261                 free( rs->sr_ctrls[0] );
1262                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1263                 rs->sr_ctrls = NULL;
1264         }
1265 #endif
1266         return 0;
1267 }
1268
1269 static void
1270 syncprov_detach_op( Operation *op, syncops *so )
1271 {
1272         Operation *op2;
1273         int i, alen = 0;
1274         size_t size;
1275         char *ptr;
1276
1277         /* count the search attrs */
1278         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1279                 alen += op->ors_attrs[i].an_name.bv_len + 1;
1280         }
1281         /* Make a new copy of the operation */
1282         size = sizeof(Operation) + sizeof(Opheader) +
1283                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
1284                 op->o_req_dn.bv_len + 1 +
1285                 op->o_req_ndn.bv_len + 1 +
1286                 op->o_ndn.bv_len + 1 +
1287                 so->s_filterstr.bv_len + 1;
1288         op2 = (Operation *)ch_malloc( size );
1289         *op2 = *op;
1290         op2->o_hdr = (Opheader *)(op2+1);
1291         *op2->o_hdr = *op->o_hdr;
1292         if ( i ) {
1293                 op2->ors_attrs = (AttributeName *)(op2->o_hdr + 1);
1294                 ptr = (char *)(op2->ors_attrs+i+1);
1295                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1296                         op2->ors_attrs[i] = op->ors_attrs[i];
1297                         op2->ors_attrs[i].an_name.bv_val = ptr;
1298                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
1299                 }
1300                 BER_BVZERO( &op2->ors_attrs[i].an_name );
1301         } else {
1302                 ptr = (char *)(op2->o_hdr + 1);
1303         }
1304         op2->o_ndn.bv_val = ptr;
1305         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
1306         op2->o_dn = op2->o_ndn;
1307         op2->o_req_dn.bv_val = ptr;
1308         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
1309         op2->o_req_ndn.bv_val = ptr;
1310         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
1311         op2->ors_filterstr.bv_val = ptr;
1312         strcpy( ptr, so->s_filterstr.bv_val );
1313         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
1314         op2->ors_filter = str2filter( ptr );
1315         op2->o_controls = NULL;
1316         op2->o_callback = NULL;
1317         so->s_op = op2;
1318
1319         /* Increment number of ops so that idletimeout ignores us */
1320         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1321         op->o_conn->c_n_ops_executing++;
1322         op->o_conn->c_n_ops_completed--;
1323         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1324 }
1325
1326 static int
1327 syncprov_search_response( Operation *op, SlapReply *rs )
1328 {
1329         searchstate *ss = op->o_callback->sc_private;
1330         slap_overinst *on = ss->ss_on;
1331         syncprov_info_t         *si = on->on_bi.bi_private;
1332         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
1333
1334         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
1335                 int i;
1336                 /* If we got a referral without a referral object, there's
1337                  * something missing that we cannot replicate. Just ignore it.
1338                  * The consumer will abort because we didn't send the expected
1339                  * control.
1340                  */
1341                 if ( !rs->sr_entry ) {
1342                         assert( rs->sr_entry );
1343                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
1344                         return SLAP_CB_CONTINUE;
1345                 }
1346                 if ( srs->sr_state.ctxcsn ) {
1347                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
1348                                 slap_schema.si_ad_entryCSN );
1349                         /* Don't send the ctx entry twice */
1350                         if ( bvmatch( &a->a_nvals[0], srs->sr_state.ctxcsn ))
1351                                 return LDAP_SUCCESS;
1352                 }
1353                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1354                         op->o_tmpmemctx );
1355                 rs->sr_ctrls[1] = NULL;
1356                 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
1357                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
1358         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
1359                 struct berval cookie;
1360
1361                 slap_compose_sync_cookie( op, &cookie,
1362                         &op->ors_filter->f_and->f_ava->aa_value,
1363                         srs->sr_state.sid, srs->sr_state.rid );
1364
1365                 /* Is this a regular refresh? */
1366                 if ( !ss->ss_so ) {
1367                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1368                                 op->o_tmpmemctx );
1369                         rs->sr_ctrls[1] = NULL;
1370                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
1371                                 0, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
1372                 } else {
1373                         int locked = 0;
1374                 /* It's RefreshAndPersist, transition to Persist phase */
1375                         syncprov_sendinfo( op, rs, rs->sr_nentries ?
1376                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
1377                                 &cookie, 1, NULL, 0 );
1378                         /* Flush any queued persist messages */
1379                         if ( ss->ss_so->s_res ) {
1380                                 syncres *sr, *srnext;
1381                                 Entry *e;
1382                                 opcookie opc;
1383
1384                                 opc.son = on;
1385                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
1386                                 locked = 1;
1387                                 for (sr = ss->ss_so->s_res; sr; sr=srnext) {
1388                                         int rc = LDAP_SUCCESS;
1389                                         srnext = sr->s_next;
1390                                         opc.sdn = sr->s_dn;
1391                                         opc.sndn = sr->s_ndn;
1392                                         opc.suuid = sr->s_uuid;
1393                                         opc.sctxcsn = sr->s_csn;
1394                                         opc.sreference = sr->s_isreference;
1395                                         e = NULL;
1396
1397                                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
1398                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1399                                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
1400                                                 op->o_bd->bd_info = (BackendInfo *)on;
1401                                         }
1402                                         if ( rc == LDAP_SUCCESS )
1403                                                 syncprov_sendresp( op, &opc, ss->ss_so, e,
1404                                                         sr->s_mode, 0 );
1405
1406                                         if ( e ) {
1407                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1408                                                 be_entry_release_r( op, e );
1409                                                 op->o_bd->bd_info = (BackendInfo *)on;
1410                                         }
1411                                         ch_free( sr );
1412                                 }
1413                                 ss->ss_so->s_res = NULL;
1414                                 ss->ss_so->s_restail = NULL;
1415                         }
1416
1417                         /* Turn off the refreshing flag */
1418                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
1419                         if ( locked )
1420                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
1421
1422                         /* Detach this Op from frontend control */
1423                         syncprov_detach_op( op, ss->ss_so );
1424
1425                         return LDAP_SUCCESS;
1426                 }
1427         }
1428
1429         return SLAP_CB_CONTINUE;
1430 }
1431
1432 static int
1433 syncprov_op_search( Operation *op, SlapReply *rs )
1434 {
1435         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1436         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1437         slap_callback   *cb;
1438         int gotstate = 0, nochange = 0;
1439         Filter *fand, *fava;
1440         syncops *sop = NULL;
1441         searchstate *ss;
1442         sync_control *srs;
1443
1444         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
1445
1446         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1447                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
1448                 return rs->sr_err;
1449         }
1450
1451         srs = op->o_controls[slap_cids.sc_LDAPsync];
1452
1453         /* If this is a persistent search, set it up right away */
1454         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
1455                 syncops so = {0};
1456                 fbase_cookie fc;
1457                 opcookie opc;
1458                 slap_callback sc;
1459
1460                 fc.fss = &so;
1461                 fc.fbase = 0;
1462                 so.s_eid = NOID;
1463                 so.s_op = op;
1464                 so.s_flags = PS_IS_REFRESHING;
1465                 /* syncprov_findbase expects to be called as a callback... */
1466                 sc.sc_private = &opc;
1467                 opc.son = on;
1468                 cb = op->o_callback;
1469                 op->o_callback = &sc;
1470                 rs->sr_err = syncprov_findbase( op, &fc );
1471                 op->o_callback = cb;
1472
1473                 if ( rs->sr_err != LDAP_SUCCESS ) {
1474                         send_ldap_result( op, rs );
1475                         return rs->sr_err;
1476                 }
1477                 sop = ch_malloc( sizeof( syncops ));
1478                 *sop = so;
1479                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
1480                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1481                 sop->s_sid = srs->sr_state.sid;
1482                 sop->s_rid = srs->sr_state.rid;
1483                 sop->s_next = si->si_ops;
1484                 sop->s_inuse = 1;
1485                 si->si_ops = sop;
1486                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1487         }
1488
1489         /* If we have a cookie, handle the PRESENT lookups
1490          */
1491         if ( srs->sr_state.ctxcsn ) {
1492                 /* Is the CSN in a valid format? */
1493                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
1494                         send_ldap_error( op, rs, LDAP_OTHER, "invalid sync cookie" );
1495                         return rs->sr_err;
1496                 }
1497                 /* Is the CSN still present in the database? */
1498                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
1499                         /* No, so a reload is required */
1500 #if 0           /* the consumer doesn't seem to send this hint */
1501                         if ( op->o_sync_rhint == 0 ) {
1502                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
1503                                 return rs->sr_err;
1504                         }
1505 #endif
1506                 } else {
1507                         gotstate = 1;
1508                         /* If just Refreshing and nothing has changed, shortcut it */
1509                         if ( bvmatch( srs->sr_state.ctxcsn, &si->si_ctxcsn )) {
1510                                 nochange = 1;
1511                                 if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
1512                                         LDAPControl     *ctrls[2];
1513
1514                                         ctrls[0] = NULL;
1515                                         ctrls[1] = NULL;
1516                                         syncprov_done_ctrl( op, rs, ctrls, 0, 0,
1517                                                 NULL, LDAP_SYNC_REFRESH_DELETES );
1518                                         rs->sr_ctrls = ctrls;
1519                                         rs->sr_err = LDAP_SUCCESS;
1520                                         send_ldap_result( op, rs );
1521                                         rs->sr_ctrls = NULL;
1522                                         return rs->sr_err;
1523                                 }
1524                                 goto shortcut;
1525                         } else
1526                         /* If context has changed, check for Present UUIDs */
1527                         if ( syncprov_findcsn( op, FIND_PRESENT ) != LDAP_SUCCESS ) {
1528                                 send_ldap_result( op, rs );
1529                                 return rs->sr_err;
1530                         }
1531                 }
1532         }
1533
1534         /* Append CSN range to search filter, save original filter
1535          * for persistent search evaluation
1536          */
1537         if ( sop ) {
1538                 sop->s_filterstr= op->ors_filterstr;
1539         }
1540
1541         fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1542         fand->f_choice = LDAP_FILTER_AND;
1543         fand->f_next = NULL;
1544         fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1545         fava->f_choice = LDAP_FILTER_LE;
1546         fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1547         fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1548         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1549         ber_dupbv_x( &fava->f_ava->aa_value, &si->si_ctxcsn, op->o_tmpmemctx );
1550         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1551         fand->f_and = fava;
1552         if ( gotstate ) {
1553                 fava->f_next = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1554                 fava = fava->f_next;
1555                 fava->f_choice = LDAP_FILTER_GE;
1556                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1557                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1558                 ber_dupbv_x( &fava->f_ava->aa_value, srs->sr_state.ctxcsn, op->o_tmpmemctx );
1559         }
1560         fava->f_next = op->ors_filter;
1561         op->ors_filter = fand;
1562         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1563
1564 shortcut:
1565         /* Let our callback add needed info to returned entries */
1566         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1567         ss = (searchstate *)(cb+1);
1568         ss->ss_on = on;
1569         ss->ss_so = sop;
1570         cb->sc_response = syncprov_search_response;
1571         cb->sc_cleanup = syncprov_search_cleanup;
1572         cb->sc_private = ss;
1573         cb->sc_next = op->o_callback;
1574         op->o_callback = cb;
1575
1576 #if 0   /* I don't think we need to shortcircuit back-bdb any more */
1577         op->o_sync_mode &= SLAP_CONTROL_MASK;
1578 #endif
1579
1580         /* If this is a persistent search and no changes were reported during
1581          * the refresh phase, just invoke the response callback to transition
1582          * us into persist phase
1583          */
1584         if ( nochange ) {
1585                 rs->sr_err = LDAP_SUCCESS;
1586                 rs->sr_nentries = 0;
1587                 send_ldap_result( op, rs );
1588                 return rs->sr_err;
1589         }
1590         return SLAP_CB_CONTINUE;
1591 }
1592
1593 static int
1594 syncprov_operational(
1595         Operation *op,
1596         SlapReply *rs )
1597 {
1598         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1599         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1600
1601         if ( rs->sr_entry &&
1602                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
1603
1604                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
1605                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
1606                         Attribute *a, **ap = NULL;
1607
1608                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
1609                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
1610                                         break;
1611                         }
1612
1613                         if ( !a ) {
1614                                 for ( ap = &rs->sr_operational_attrs; *ap; ap=&(*ap)->a_next );
1615
1616                                 a = ch_malloc( sizeof(Attribute));
1617                                 a->a_desc = slap_schema.si_ad_contextCSN;
1618                                 a->a_vals = ch_malloc( 2 * sizeof(struct berval));
1619                                 a->a_vals[1].bv_val = NULL;
1620                                 a->a_nvals = a->a_vals;
1621                                 a->a_next = NULL;
1622                                 a->a_flags = 0;
1623                                 *ap = a;
1624                         }
1625
1626                         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1627                         if ( !ap ) {
1628                                 strcpy( a->a_vals[0].bv_val, si->si_ctxcsnbuf );
1629                         } else {
1630                                 ber_dupbv( &a->a_vals[0], &si->si_ctxcsn );
1631                         }
1632                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1633                 }
1634         }
1635         return SLAP_CB_CONTINUE;
1636 }
1637
1638 static int
1639 syncprov_db_config(
1640         BackendDB       *be,
1641         const char      *fname,
1642         int             lineno,
1643         int             argc,
1644         char    **argv
1645 )
1646 {
1647         slap_overinst           *on = (slap_overinst *)be->bd_info;
1648         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1649
1650         if ( strcasecmp( argv[ 0 ], "syncprov-checkpoint" ) == 0 ) {
1651                 if ( argc != 3 ) {
1652                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1653                                 "\"syncprov-checkpoint <ops> <minutes>\"\n", fname, lineno );
1654                         return -1;
1655                 }
1656                 si->si_chkops = atoi( argv[1] );
1657                 si->si_chktime = atoi( argv[2] ) * 60;
1658                 return 0;
1659
1660         }
1661
1662         return SLAP_CONF_UNKNOWN;
1663 }
1664
1665 /* Cheating - we have no thread pool context for these functions,
1666  * so make one.
1667  */
1668 typedef struct thread_keys {
1669         void *key;
1670         void *data;
1671         ldap_pvt_thread_pool_keyfree_t *xfree;
1672 } thread_keys;
1673
1674 #define MAXKEYS 32
1675 /* A fake thread context */
1676 static thread_keys thrctx[MAXKEYS];
1677
1678 /* Read any existing contextCSN from the underlying db.
1679  * Then search for any entries newer than that. If no value exists,
1680  * just generate it. Cache whatever result.
1681  */
1682 static int
1683 syncprov_db_open(
1684     BackendDB *be
1685 )
1686 {
1687         slap_overinst   *on = (slap_overinst *) be->bd_info;
1688         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1689
1690         Connection conn;
1691         char opbuf[OPERATION_BUFFER_SIZE];
1692         Operation *op = (Operation *)opbuf;
1693         Entry *e;
1694         Attribute *a;
1695         int rc;
1696
1697         connection_fake_init( &conn, op, thrctx );
1698         op->o_bd = be;
1699         op->o_dn = be->be_rootdn;
1700         op->o_ndn = be->be_rootndn;
1701
1702         op->o_bd->bd_info = on->on_info->oi_orig;
1703         rc = be_entry_get_rw( op, be->be_nsuffix, NULL,
1704                 slap_schema.si_ad_contextCSN, 0, &e );
1705
1706         if ( e ) {
1707                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
1708                 if ( a ) {
1709                         si->si_ctxcsn.bv_len = a->a_nvals[0].bv_len;
1710                         if ( si->si_ctxcsn.bv_len >= sizeof(si->si_ctxcsnbuf ))
1711                                 si->si_ctxcsn.bv_len = sizeof(si->si_ctxcsnbuf)-1;
1712                         strncpy( si->si_ctxcsnbuf, a->a_nvals[0].bv_val,
1713                                 si->si_ctxcsn.bv_len );
1714                         si->si_ctxcsnbuf[si->si_ctxcsn.bv_len] = '\0';
1715                 }
1716                 be_entry_release_r( op, e );
1717                 op->o_bd->bd_info = (BackendInfo *)on;
1718                 op->o_req_dn = be->be_suffix[0];
1719                 op->o_req_ndn = be->be_nsuffix[0];
1720                 op->ors_scope = LDAP_SCOPE_SUBTREE;
1721                 syncprov_findcsn( op, FIND_MAXCSN );
1722         }
1723
1724         if ( BER_BVISEMPTY( &si->si_ctxcsn ) ) {
1725                 slap_get_csn( op, si->si_ctxcsnbuf, sizeof(si->si_ctxcsnbuf),
1726                                 &si->si_ctxcsn, 0 );
1727         }
1728
1729         op->o_bd->bd_info = (BackendInfo *)on;
1730         return 0;
1731 }
1732
1733 /* Write the current contextCSN into the underlying db.
1734  */
1735 static int
1736 syncprov_db_close(
1737     BackendDB *be
1738 )
1739 {
1740     slap_overinst   *on = (slap_overinst *) be->bd_info;
1741     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1742         int i;
1743
1744         if ( si->si_numops ) {
1745                 Connection conn;
1746                 char opbuf[OPERATION_BUFFER_SIZE];
1747                 Operation *op = (Operation *)opbuf;
1748                 SlapReply rs = {REP_RESULT};
1749
1750                 connection_fake_init( &conn, op, thrctx );
1751                 op->o_bd = be;
1752                 op->o_dn = be->be_rootdn;
1753                 op->o_ndn = be->be_rootndn;
1754                 syncprov_checkpoint( op, &rs, on );
1755         }
1756         for ( i=0; thrctx[i].key; i++) {
1757                 if ( thrctx[i].xfree )
1758                         thrctx[i].xfree( thrctx[i].key, thrctx[i].data );
1759                 thrctx[i].key = NULL;
1760         }
1761
1762     return 0;
1763 }
1764
1765 static int
1766 syncprov_db_init(
1767         BackendDB *be
1768 )
1769 {
1770         slap_overinst   *on = (slap_overinst *)be->bd_info;
1771         syncprov_info_t *si;
1772
1773         si = ch_calloc(1, sizeof(syncprov_info_t));
1774         on->on_bi.bi_private = si;
1775         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
1776         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
1777         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
1778         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
1779
1780         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
1781         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
1782
1783         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
1784         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1785
1786         return 0;
1787 }
1788
1789 static int
1790 syncprov_db_destroy(
1791         BackendDB *be
1792 )
1793 {
1794         slap_overinst   *on = (slap_overinst *)be->bd_info;
1795         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1796
1797         if ( si ) {
1798                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
1799                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
1800                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
1801                 ch_free( si );
1802         }
1803
1804         return 0;
1805 }
1806
1807 static int syncprov_parseCtrl (
1808         Operation *op,
1809         SlapReply *rs,
1810         LDAPControl *ctrl )
1811 {
1812         ber_tag_t tag;
1813         BerElement *ber;
1814         ber_int_t mode;
1815         ber_len_t len;
1816         struct berval cookie = BER_BVNULL;
1817         sync_control *sr;
1818         int rhint = 0;
1819
1820         if ( op->o_sync != SLAP_CONTROL_NONE ) {
1821                 rs->sr_text = "Sync control specified multiple times";
1822                 return LDAP_PROTOCOL_ERROR;
1823         }
1824
1825         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
1826                 rs->sr_text = "Sync control specified with pagedResults control";
1827                 return LDAP_PROTOCOL_ERROR;
1828         }
1829
1830         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
1831                 rs->sr_text = "Sync control value is empty (or absent)";
1832                 return LDAP_PROTOCOL_ERROR;
1833         }
1834
1835         /* Parse the control value
1836          *      syncRequestValue ::= SEQUENCE {
1837          *              mode   ENUMERATED {
1838          *                      -- 0 unused
1839          *                      refreshOnly             (1),
1840          *                      -- 2 reserved
1841          *                      refreshAndPersist       (3)
1842          *              },
1843          *              cookie  syncCookie OPTIONAL
1844          *      }
1845          */
1846
1847         ber = ber_init( &ctrl->ldctl_value );
1848         if( ber == NULL ) {
1849                 rs->sr_text = "internal error";
1850                 return LDAP_OTHER;
1851         }
1852
1853         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
1854                 rs->sr_text = "Sync control : mode decoding error";
1855                 return LDAP_PROTOCOL_ERROR;
1856         }
1857
1858         switch( mode ) {
1859         case LDAP_SYNC_REFRESH_ONLY:
1860                 mode = SLAP_SYNC_REFRESH;
1861                 break;
1862         case LDAP_SYNC_REFRESH_AND_PERSIST:
1863                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
1864                 break;
1865         default:
1866                 rs->sr_text = "Sync control : unknown update mode";
1867                 return LDAP_PROTOCOL_ERROR;
1868         }
1869
1870         tag = ber_peek_tag( ber, &len );
1871
1872         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
1873                 if (( ber_scanf( ber, /*{*/ "o", &cookie )) == LBER_ERROR ) {
1874                         rs->sr_text = "Sync control : cookie decoding error";
1875                         return LDAP_PROTOCOL_ERROR;
1876                 }
1877         }
1878         if ( tag == LDAP_TAG_RELOAD_HINT ) {
1879                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
1880                         rs->sr_text = "Sync control : rhint decoding error";
1881                         return LDAP_PROTOCOL_ERROR;
1882                 }
1883         }
1884         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
1885                         rs->sr_text = "Sync control : decoding error";
1886                         return LDAP_PROTOCOL_ERROR;
1887         }
1888         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
1889         sr->sr_rhint = rhint;
1890         if (!BER_BVISNULL(&cookie)) {
1891                 ber_bvarray_add( &sr->sr_state.octet_str, &cookie );
1892                 slap_parse_sync_cookie( &sr->sr_state );
1893         }
1894
1895         op->o_controls[slap_cids.sc_LDAPsync] = sr;
1896
1897         (void) ber_free( ber, 1 );
1898
1899         op->o_sync = ctrl->ldctl_iscritical
1900                 ? SLAP_CONTROL_CRITICAL
1901                 : SLAP_CONTROL_NONCRITICAL;
1902
1903         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
1904
1905         return LDAP_SUCCESS;
1906 }
1907
1908 /* This overlay is set up for dynamic loading via moduleload. For static
1909  * configuration, you'll need to arrange for the slap_overinst to be
1910  * initialized and registered by some other function inside slapd.
1911  */
1912
1913 static slap_overinst            syncprov;
1914
1915 int
1916 syncprov_init()
1917 {
1918         int rc;
1919
1920         rc = register_supported_control( LDAP_CONTROL_SYNC,
1921                 SLAP_CTRL_HIDE|SLAP_CTRL_SEARCH, NULL,
1922                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
1923         if ( rc != LDAP_SUCCESS ) {
1924                 fprintf( stderr, "Failed to register control %d\n", rc );
1925                 return rc;
1926         }
1927
1928         syncprov.on_bi.bi_type = "syncprov";
1929         syncprov.on_bi.bi_db_init = syncprov_db_init;
1930         syncprov.on_bi.bi_db_config = syncprov_db_config;
1931         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
1932         syncprov.on_bi.bi_db_open = syncprov_db_open;
1933         syncprov.on_bi.bi_db_close = syncprov_db_close;
1934
1935         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
1936         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
1937
1938         syncprov.on_bi.bi_op_add = syncprov_op_mod;
1939         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
1940         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
1941         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
1942         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
1943         syncprov.on_bi.bi_op_search = syncprov_op_search;
1944         syncprov.on_bi.bi_extended = syncprov_op_extended;
1945         syncprov.on_bi.bi_operational = syncprov_operational;
1946
1947         return overlay_register( &syncprov );
1948 }
1949
1950 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
1951 int
1952 init_module( int argc, char *argv[] )
1953 {
1954         return syncprov_init();
1955 }
1956 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
1957
1958 #endif /* defined(SLAPD_OVER_SYNCPROV) */