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