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