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