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