]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
Added response queuing for updates occurring during a refresh
[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 queued result of a persistent search */
29 typedef struct syncres {
30         struct syncres *s_next;
31         struct berval s_dn;
32         struct berval s_ndn;
33         struct berval s_uuid;
34         struct berval s_csn;
35         char s_mode;
36         char s_isreference;
37 } syncres;
38
39 /* Record of a persistent search */
40 typedef struct syncops {
41         struct syncops *s_next;
42         struct berval   s_base;         /* ndn of search base */
43         ID              s_eid;          /* entryID of search base */
44         Operation       *s_op;          /* search op */
45         Filter  *s_filter;
46         int             s_flags;        /* search status */
47         struct syncres *s_res;
48         struct syncres *s_restail;
49         ldap_pvt_thread_mutex_t s_mutex;
50 } syncops;
51
52 static int      sync_cid;
53
54 #define PS_IS_REFRESHING        0x01
55
56 /* Record of which searches matched at premodify step */
57 typedef struct syncmatches {
58         struct syncmatches *sm_next;
59         syncops *sm_op;
60 } syncmatches;
61
62 typedef struct syncprov_info_t {
63         syncops         *si_ops;
64         struct berval   si_ctxcsn;      /* ldapsync context */
65         int             si_gotcsn;      /* is our ctxcsn up to date? */
66         ldap_pvt_thread_mutex_t si_csn_mutex;
67         ldap_pvt_thread_mutex_t si_ops_mutex;
68         char            si_ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
69 } syncprov_info_t;
70
71 typedef struct opcookie {
72         slap_overinst *son;
73         syncmatches *smatches;
74         struct berval sdn;      /* DN of entry, for deletes */
75         struct berval sndn;
76         struct berval suuid;    /* UUID of entry */
77         struct berval sctxcsn;
78         int sreference; /* Is the entry a reference? */
79 } opcookie;
80
81 typedef struct fbase_cookie {
82         struct berval *fdn;     /* DN of a modified entry, for scope testing */
83         syncops *fss;   /* persistent search we're testing against */
84         int fbase;      /* if TRUE we found the search base and it's still valid */
85         int fscope;     /* if TRUE then fdn is within the psearch scope */
86 } fbase_cookie;
87
88 static AttributeName csn_anlist[2];
89 static AttributeName uuid_anlist[2];
90
91 /* syncprov_findbase:
92  *   finds the true DN of the base of a search (with alias dereferencing) and
93  * checks to make sure the base entry doesn't get replaced with a different
94  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
95  * change is detected, any persistent search on this base must be terminated /
96  * reloaded.
97  *   On the first call, we just save the DN and entryID. On subsequent calls
98  * we compare the DN and entryID with the saved values.
99  */
100 static int
101 findbase_cb( Operation *op, SlapReply *rs )
102 {
103         slap_callback *sc = op->o_callback;
104
105         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
106                 fbase_cookie *fc = sc->sc_private;
107
108                 /* If no entryID, we're looking for the first time.
109                  * Just store whatever we got.
110                  */
111                 if ( fc->fss->s_eid == NOID ) {
112                         fc->fbase = 1;
113                         fc->fss->s_eid = rs->sr_entry->e_id;
114                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
115
116                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
117                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
118
119                 /* OK, the DN is the same and the entryID is the same. Now
120                  * see if the fdn resides in the scope.
121                  */
122                         fc->fbase = 1;
123                         switch ( fc->fss->s_op->ors_scope ) {
124                         case LDAP_SCOPE_BASE:
125                                 fc->fscope = dn_match( fc->fdn, &rs->sr_entry->e_nname );
126                                 break;
127                         case LDAP_SCOPE_ONELEVEL: {
128                                 struct berval pdn;
129                                 dnParent( fc->fdn, &pdn );
130                                 fc->fscope = dn_match( &pdn, &rs->sr_entry->e_nname );
131                                 break; }
132                         case LDAP_SCOPE_SUBTREE:
133                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname );
134                                 break;
135 #ifdef LDAP_SCOPE_SUBORDINATE
136                         case LDAP_SCOPE_SUBORDINATE:
137                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname ) &&
138                                         !dn_match( fc->fdn, &rs->sr_entry->e_nname );
139                                 break;
140 #endif
141                         }
142                 }
143         }
144         return LDAP_SUCCESS;
145 }
146
147 static int
148 syncprov_findbase( Operation *op, fbase_cookie *fc )
149 {
150         opcookie *opc = op->o_callback->sc_private;
151         slap_overinst *on = opc->son;
152         syncprov_info_t         *si = on->on_bi.bi_private;
153
154         slap_callback cb = {0};
155         Operation fop;
156         SlapReply frs = { REP_RESULT };
157         int rc;
158
159         fop = *op;
160
161         cb.sc_response = findbase_cb;
162         cb.sc_private = fc;
163
164         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync mode */
165         fop.o_callback = &cb;
166         fop.o_tag = LDAP_REQ_SEARCH;
167         fop.ors_scope = LDAP_SCOPE_BASE;
168         fop.ors_deref = fc->fss->s_op->ors_deref;
169         fop.ors_slimit = 1;
170         fop.ors_tlimit = SLAP_NO_LIMIT;
171         fop.ors_attrs = slap_anlist_no_attrs;
172         fop.ors_attrsonly = 1;
173         fop.ors_filter = fc->fss->s_op->ors_filter;
174         fop.ors_filterstr = fc->fss->s_op->ors_filterstr;
175
176         fop.o_req_ndn = fc->fss->s_op->o_req_ndn;
177
178         fop.o_bd->bd_info = on->on_info->oi_orig;
179         rc = fop.o_bd->be_search( &fop, &frs );
180         fop.o_bd->bd_info = (BackendInfo *)on;
181
182         if ( fc->fbase ) return LDAP_SUCCESS;
183
184         /* If entryID has changed, then the base of this search has
185          * changed. Invalidate the psearch.
186          */
187         return LDAP_NO_SUCH_OBJECT;
188 }
189
190 /* syncprov_findcsn:
191  *   This function has three different purposes, but they all use a search
192  * that filters on entryCSN so they're combined here.
193  * 1: when the current contextCSN is unknown (i.e., at server start time)
194  * and a syncrepl search has arrived with a cookie, we search for all entries
195  * with CSN >= the cookie CSN, and store the maximum as our contextCSN. Also,
196  * we expect to find the cookie CSN in the search results, and note if we did
197  * or not. If not, we assume the cookie is stale. (This may be too restrictive,
198  * notice case 2.)
199  *
200  * 2: when the current contextCSN is known and we have a sync cookie, we search
201  * for one entry with CSN <= the cookie CSN. (Used to search for =.) If an
202  * entry is found, the cookie CSN is valid, otherwise it is stale. Case 1 is
203  * considered a special case of case 2, and both are generally called the
204  * "find CSN" task.
205  *
206  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
207  * CSN, and generate Present records for them. We always collect this result
208  * in SyncID sets, even if there's only one match.
209  */
210 #define FIND_CSN        1
211 #define FIND_PRESENT    2
212
213 typedef struct fcsn_cookie {
214         struct berval maxcsn;
215         int gotmatch;
216 } fcsn_cookie;
217
218 static int
219 findcsn_cb( Operation *op, SlapReply *rs )
220 {
221         slap_callback *sc = op->o_callback;
222
223         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
224                 /* If the private pointer is set, it points to an fcsn_cookie
225                  * and we want to record the maxcsn and match state.
226                  */
227                 if ( sc->sc_private ) {
228                         int i;
229                         fcsn_cookie *fc = sc->sc_private;
230                         syncrepl_state *srs = op->o_controls[sync_cid];
231                         Attribute *a = attr_find(rs->sr_entry->e_attrs,
232                                 slap_schema.si_ad_entryCSN );
233                         i = ber_bvcmp( &a->a_vals[0], srs->sr_state.ctxcsn );
234                         if ( i == 0 ) fc->gotmatch = 1;
235                         i = ber_bvcmp( &a->a_vals[0], &fc->maxcsn );
236                         if ( i > 0 ) {
237                                 fc->maxcsn.bv_len = a->a_vals[0].bv_len;
238                                 strcpy(fc->maxcsn.bv_val, a->a_vals[0].bv_val );
239                         }
240                 } else {
241                 /* Otherwise, if the private pointer is not set, we just
242                  * want to know if any entry matched the filter.
243                  */
244                         sc->sc_private = (void *)1;
245                 }
246         }
247         return LDAP_SUCCESS;
248 }
249
250 /* Build a list of entryUUIDs for sending in a SyncID set */
251
252 typedef struct fpres_cookie {
253         int num;
254         BerVarray uuids;
255 } fpres_cookie;
256
257 static int
258 findpres_cb( Operation *op, SlapReply *rs )
259 {
260         slap_callback *sc = op->o_callback;
261         fpres_cookie *pc = sc->sc_private;
262         int ret = SLAP_CB_CONTINUE;
263
264         if ( rs->sr_type == REP_SEARCH ) {
265                 ret = slap_build_syncUUID_set( op, &pc->uuids, rs->sr_entry );
266                 if ( ret > 0 ) {
267                         pc->num++;
268                         ret = LDAP_SUCCESS;
269                         if ( pc->num == SLAP_SYNCUUID_SET_SIZE ) {
270                                 rs->sr_rspoid = LDAP_SYNC_INFO;
271                                 ret = slap_send_syncinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
272                                         0, pc->uuids, 0 );
273                                 ber_bvarray_free_x( pc->uuids, op->o_tmpmemctx );
274                                 pc->uuids = NULL;
275                                 pc->num = 0;
276                         }
277                 } else {
278                         ret = LDAP_OTHER;
279                 }
280         } else if ( rs->sr_type == REP_RESULT ) {
281                 ret = rs->sr_err;
282                 if ( pc->num ) {
283                         rs->sr_rspoid = LDAP_SYNC_INFO;
284                         ret = slap_send_syncinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
285                                 0, pc->uuids, 0 );
286                         ber_bvarray_free_x( pc->uuids, op->o_tmpmemctx );
287                         pc->uuids = NULL;
288                         pc->num = 0;
289                 }
290         }
291         return ret;
292 }
293
294
295 static int
296 syncprov_findcsn( Operation *op, int mode )
297 {
298         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
299         syncprov_info_t         *si = on->on_bi.bi_private;
300
301         slap_callback cb = {0};
302         Operation fop;
303         SlapReply frs = { REP_RESULT };
304         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
305         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
306         struct berval fbuf;
307         Filter cf;
308         AttributeAssertion eq;
309         int rc;
310         fcsn_cookie fcookie;
311         fpres_cookie pcookie;
312         int locked = 0;
313         syncrepl_state *srs = op->o_controls[sync_cid];
314
315         if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
316                 return LDAP_OTHER;
317         }
318
319         fop = *op;
320         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
321
322         fbuf.bv_val = buf;
323         if ( mode == FIND_CSN ) {
324                 if ( !si->si_gotcsn ) {
325                         /* If we don't know the current ctxcsn, find it */
326                         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
327                         locked = 1;
328                 }
329                 if ( !si->si_gotcsn ) {
330                         cf.f_choice = LDAP_FILTER_GE;
331                         fop.ors_attrsonly = 0;
332                         fop.ors_attrs = csn_anlist;
333                         fop.ors_slimit = SLAP_NO_LIMIT;
334                         cb.sc_private = &fcookie;
335                         fcookie.maxcsn.bv_val = cbuf;
336                         fcookie.maxcsn.bv_len = 0;
337                         fcookie.gotmatch = 0;
338                         fbuf.bv_len = sprintf( buf, "(entryCSN>=%s)", srs->sr_state.ctxcsn->bv_val );
339                 } else {
340                         if ( locked ) {
341                                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
342                                 locked = 0;
343                         }
344                         cf.f_choice = LDAP_FILTER_LE;
345                         fop.ors_attrsonly = 1;
346                         fop.ors_attrs = slap_anlist_no_attrs;
347                         fop.ors_slimit = 1;
348                         cb.sc_private = NULL;
349                         fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)", srs->sr_state.ctxcsn->bv_val );
350                 }
351                 cb.sc_response = findcsn_cb;
352
353         } else if ( mode == FIND_PRESENT ) {
354                 cf.f_choice = LDAP_FILTER_LE;
355                 fop.ors_attrsonly = 0;
356                 fop.ors_attrs = uuid_anlist;
357                 fop.ors_slimit = SLAP_NO_LIMIT;
358                 /* We want pure entries, not referrals */
359                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
360                 cb.sc_private = &pcookie;
361                 cb.sc_response = findpres_cb;
362                 pcookie.num = 0;
363                 pcookie.uuids = NULL;
364                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)", srs->sr_state.ctxcsn->bv_val );
365         }
366         cf.f_ava = &eq;
367         cf.f_av_desc = slap_schema.si_ad_entryCSN;
368         cf.f_av_value = *srs->sr_state.ctxcsn;
369         cf.f_next = NULL;
370
371         fop.o_callback = &cb;
372         fop.ors_tlimit = SLAP_NO_LIMIT;
373         fop.ors_filter = &cf;
374         fop.ors_filterstr = fbuf;
375
376         fop.o_bd->bd_info = on->on_info->oi_orig;
377         rc = fop.o_bd->be_search( &fop, &frs );
378         fop.o_bd->bd_info = (BackendInfo *)on;
379
380         if ( mode == FIND_CSN ) {
381                 if ( !si->si_gotcsn ) {
382                         strcpy(si->si_ctxcsnbuf, fcookie.maxcsn.bv_val);
383                         si->si_ctxcsn.bv_len = fcookie.maxcsn.bv_len;
384                         si->si_gotcsn = 1;
385                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
386                         if ( fcookie.gotmatch ) return LDAP_SUCCESS;
387                         
388                 } else {
389                         if ( cb.sc_private ) return LDAP_SUCCESS;
390                 }
391         } else if ( mode == FIND_PRESENT ) {
392                 return LDAP_SUCCESS;
393         }
394
395         /* If matching CSN was not found, invalidate the context. */
396         return LDAP_NO_SUCH_OBJECT;
397 }
398
399 /* Queue a persistent search response if still in Refresh stage */
400 static int
401 syncprov_qresp( opcookie *opc, syncops *so, int mode )
402 {
403         syncres *sr;
404
405         sr = ch_malloc(sizeof(syncres) + opc->suuid.bv_len + 1 +
406                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1 + opc->sctxcsn.bv_len + 1 );
407         sr->s_next = NULL;
408         sr->s_dn.bv_val = (char *)(sr + 1);
409         sr->s_mode = mode;
410         sr->s_isreference = opc->sreference;
411         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val, opc->sdn.bv_val );
412         *(sr->s_ndn.bv_val++) = '\0';
413         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val, opc->sndn.bv_val );
414         *(sr->s_uuid.bv_val++) = '\0';
415         sr->s_csn.bv_val = lutil_strcopy( sr->s_uuid.bv_val, opc->suuid.bv_val );
416
417         if ( !so->s_res ) {
418                 so->s_res = sr;
419         } else {
420                 so->s_restail->s_next = sr;
421         }
422         so->s_restail = sr;
423         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
424         return LDAP_SUCCESS;
425 }
426
427 /* Send a persistent search response */
428 static int
429 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, Entry *e, int mode, int queue )
430 {
431         slap_overinst *on = opc->son;
432         syncprov_info_t *si = on->on_bi.bi_private;
433
434         SlapReply rs = { REP_SEARCH };
435         LDAPControl *ctrls[2];
436         struct berval cookie;
437         Entry e_uuid = {0};
438         Attribute a_uuid = {0};
439         Operation sop = *so->s_op;
440         Opheader ohdr;
441         syncrepl_state *srs = sop.o_controls[sync_cid];
442
443         ohdr = *sop.o_hdr;
444         sop.o_hdr = &ohdr;
445         sop.o_tmpmemctx = op->o_tmpmemctx;
446
447         if ( queue && (so->s_flags & PS_IS_REFRESHING) ) {
448                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
449                 if ( so->s_flags & PS_IS_REFRESHING )
450                         return syncprov_qresp( opc, so, mode );
451                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
452         }
453
454         ctrls[1] = NULL;
455         slap_compose_sync_cookie( op, &cookie, &opc->sctxcsn,
456                 srs->sr_state.sid, srs->sr_state.rid );
457
458         e_uuid.e_attrs = &a_uuid;
459         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
460         a_uuid.a_nvals = &opc->suuid;
461         rs.sr_err = slap_build_sync_state_ctrl( &sop, &rs, &e_uuid,
462                 mode, ctrls, 0, 1, &cookie );
463
464         rs.sr_entry = e;
465         rs.sr_ctrls = ctrls;
466         switch( mode ) {
467         case LDAP_SYNC_ADD:
468                 if ( opc->sreference ) {
469                         rs.sr_ref = get_entry_referrals( &sop, e );
470                         send_search_reference( &sop, &rs );
471                         ber_bvarray_free( rs.sr_ref );
472                         break;
473                 }
474                 /* fallthru */
475         case LDAP_SYNC_MODIFY:
476                 rs.sr_attrs = sop.ors_attrs;
477                 send_search_entry( &sop, &rs );
478                 break;
479         case LDAP_SYNC_DELETE:
480                 e_uuid.e_attrs = NULL;
481                 e_uuid.e_name = opc->sdn;
482                 e_uuid.e_nname = opc->sndn;
483                 rs.sr_entry = &e_uuid;
484                 if ( opc->sreference ) {
485                         struct berval bv;
486                         bv.bv_val = NULL;
487                         bv.bv_len = 0;
488                         rs.sr_ref = &bv;
489                         send_search_reference( &sop, &rs );
490                 } else {
491                         send_search_entry( &sop, &rs );
492                 }
493                 break;
494         default:
495                 assert(0);
496         }
497         free( rs.sr_ctrls[0] );
498         return rs.sr_err;
499 }
500
501 static void
502 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
503 {
504         slap_overinst *on = opc->son;
505         syncprov_info_t         *si = on->on_bi.bi_private;
506
507         fbase_cookie fc;
508         syncops *ss;
509         Entry *e;
510         Attribute *a;
511         int rc;
512         struct berval newdn;
513
514         fc.fdn = &op->o_req_ndn;
515         /* compute new DN */
516         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
517                 struct berval pdn;
518                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
519                 else dnParent( fc.fdn, &pdn );
520                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
521                 fc.fdn = &newdn;
522         }
523         if ( op->o_tag != LDAP_REQ_ADD ) {
524                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
525                 rc = be_entry_get_rw( op, fc.fdn, NULL, NULL, 0, &e );
526                 op->o_bd->bd_info = (BackendInfo *)on;
527                 if ( rc ) return;
528         } else {
529                 e = op->ora_e;
530         }
531
532         if ( saveit ) {
533                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
534                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
535                 opc->sreference = is_entry_referral( e );
536         }
537         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
538                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
539                 if ( a )
540                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
541         }
542
543         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
544         for (ss = si->si_ops; ss; ss=ss->s_next)
545         {
546                 syncmatches *sm;
547                 int found = 0;
548
549                 /* validate base */
550                 fc.fss = ss;
551                 fc.fbase = 0;
552                 fc.fscope = 0;
553                 rc = syncprov_findbase( op, &fc );
554                 if ( rc != LDAP_SUCCESS ) continue;
555
556                 /* If we're sending results now, look for this op in old matches */
557                 if ( !saveit ) {
558                         syncmatches *old;
559                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
560                                 old=sm, sm=sm->sm_next ) {
561                                 if ( sm->sm_op == ss ) {
562                                         found = 1;
563                                         old->sm_next = sm->sm_next;
564                                         op->o_tmpfree( sm, op->o_tmpmemctx );
565                                         break;
566                                 }
567                         }
568                 }
569
570                 /* check if current o_req_dn is in scope and matches filter */
571                 if ( fc.fscope && test_filter( op, e, ss->s_filter ) ==
572                         LDAP_COMPARE_TRUE ) {
573                         if ( saveit ) {
574                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
575                                 sm->sm_next = opc->smatches;
576                                 sm->sm_op = ss;
577                                 opc->smatches = sm;
578                         } else {
579                                 /* if found send UPDATE else send ADD */
580                                 syncprov_sendresp( op, opc, ss, e,
581                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD, 1 );
582                         }
583                 } else if ( !saveit && found ) {
584                         /* send DELETE */
585                         syncprov_sendresp( op, opc, ss, NULL, LDAP_SYNC_DELETE, 1 );
586                 }
587         }
588         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
589         if ( op->o_tag != LDAP_REQ_ADD ) {
590                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
591                 be_entry_release_r( op, e );
592                 op->o_bd->bd_info = (BackendInfo *)on;
593         }
594 }
595
596 static int
597 syncprov_op_cleanup( Operation *op, SlapReply *rs )
598 {
599         slap_callback *cb = op->o_callback;
600         opcookie *opc = cb->sc_private;
601         syncmatches *sm, *snext;
602
603         for (sm = opc->smatches; sm; sm=snext) {
604                 snext = sm->sm_next;
605                 op->o_tmpfree( sm, op->o_tmpmemctx );
606         }
607         op->o_callback = cb->sc_next;
608         op->o_tmpfree(cb, op->o_tmpmemctx);
609 }
610
611 static int
612 syncprov_op_response( Operation *op, SlapReply *rs )
613 {
614         opcookie *opc = op->o_callback->sc_private;
615         slap_overinst *on = opc->son;
616         syncprov_info_t         *si = on->on_bi.bi_private;
617         syncmatches *sm;
618
619         if ( rs->sr_err == LDAP_SUCCESS )
620         {
621                 struct berval maxcsn;
622                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
623
624                 cbuf[0] = '\0';
625                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
626                 slap_get_commit_csn( op, &maxcsn );
627                 if ( maxcsn.bv_val ) {
628                         strcpy( cbuf, maxcsn.bv_val );
629                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn ) > 0 ) {
630                                 strcpy( si->si_ctxcsnbuf, cbuf );
631                                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
632                         }
633                         si->si_gotcsn = 1;
634                 }
635                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
636
637                 opc->sctxcsn.bv_len = maxcsn.bv_len;
638                 opc->sctxcsn.bv_val = cbuf;
639
640                 if ( si->si_ops ) {
641                         switch(op->o_tag) {
642                         case LDAP_REQ_ADD:
643                         case LDAP_REQ_MODIFY:
644                         case LDAP_REQ_MODRDN:
645                         case LDAP_REQ_EXTENDED:
646                                 syncprov_matchops( op, opc, 0 );
647                                 break;
648                         case LDAP_REQ_DELETE:
649                                 /* for each match in opc->smatches:
650                                  *   send DELETE msg
651                                  */
652                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
653                                         syncprov_sendresp( op, opc, sm->sm_op, NULL,
654                                                 LDAP_SYNC_DELETE, 1 );
655                                 }
656                                 break;
657                         }
658                 }
659
660         }
661         return SLAP_CB_CONTINUE;
662 }
663
664 #if 0
665 static int
666 syncprov_op_compare( Operation *op, SlapReply *rs )
667 {
668         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
669         syncprov_info_t         *si = on->on_bi.bi_private;
670         int rc = SLAP_CB_CONTINUE;
671
672         if ( dn_match( &op->o_req_ndn, &si->si_e->e_nname ) )
673         {
674                 Attribute *a;
675
676                 ldap_pvt_thread_mutex_lock( &si->si_e_mutex );
677
678                 if ( get_assert( op ) &&
679                         ( test_filter( op, si->si_e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
680                 {
681                         rs->sr_err = LDAP_ASSERTION_FAILED;
682                         goto return_results;
683                 }
684
685                 rs->sr_err = access_allowed( op, si->si_e, op->oq_compare.rs_ava->aa_desc,
686                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
687                 if ( ! rs->sr_err ) {
688                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
689                         goto return_results;
690                 }
691
692                 rs->sr_err = LDAP_NO_SUCH_ATTRIBUTE;
693
694                 for ( a = attr_find( si->si_e->e_attrs, op->oq_compare.rs_ava->aa_desc );
695                         a != NULL;
696                         a = attr_find( a->a_next, op->oq_compare.rs_ava->aa_desc ) )
697                 {
698                         rs->sr_err = LDAP_COMPARE_FALSE;
699
700                         if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
701                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
702                                         SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
703                                 a->a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
704                         {
705                                 rs->sr_err = LDAP_COMPARE_TRUE;
706                                 break;
707                         }
708                 }
709
710 return_results:;
711
712                 ldap_pvt_thread_mutex_unlock( &si->si_e_mutex );
713
714                 send_ldap_result( op, rs );
715
716                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
717                         rs->sr_err = LDAP_SUCCESS;
718                 }
719                 rc = rs->sr_err;
720         }
721
722         return SLAP_CB_CONTINUE;
723 }
724 #endif
725         
726 static int
727 syncprov_op_mod( Operation *op, SlapReply *rs )
728 {
729         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
730         syncprov_info_t         *si = on->on_bi.bi_private;
731
732         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(opcookie), op->o_tmpmemctx);
733         opcookie *opc = (opcookie *)(cb+1);
734         opc->son = on;
735         cb->sc_response = syncprov_op_response;
736         cb->sc_cleanup = syncprov_op_cleanup;
737         cb->sc_private = opc;
738         cb->sc_next = op->o_callback;
739         op->o_callback = cb;
740
741         if ( si->si_ops && op->o_tag != LDAP_REQ_ADD )
742                 syncprov_matchops( op, opc, 1 );
743
744         return SLAP_CB_CONTINUE;
745 }
746
747 static int
748 syncprov_op_extended( Operation *op, SlapReply *rs )
749 {
750         if ( exop_is_write( op ))
751                 return syncprov_op_mod( op, rs );
752
753         return SLAP_CB_CONTINUE;
754 }
755
756 typedef struct searchstate {
757         slap_overinst *ss_on;
758         syncops *ss_so;
759         int ss_done;
760 } searchstate;
761
762 static int
763 syncprov_search_cleanup( Operation *op, SlapReply *rs )
764 {
765         searchstate *ss = op->o_callback->sc_private;
766         if ( rs->sr_ctrls ) {
767                 free( rs->sr_ctrls[0] );
768                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
769         }
770         if ( ss->ss_done )
771                 op->o_sync_mode |= SLAP_SYNC_REFRESH_AND_PERSIST;
772         return 0;
773 }
774
775 static int
776 syncprov_search_response( Operation *op, SlapReply *rs )
777 {
778         searchstate *ss = op->o_callback->sc_private;
779         slap_overinst *on = ss->ss_on;
780         syncprov_info_t         *si = on->on_bi.bi_private;
781         syncrepl_state *srs = op->o_controls[sync_cid];
782
783         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
784                 int i;
785                 if ( srs->sr_state.ctxcsn ) {
786                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
787                                 slap_schema.si_ad_entryCSN );
788                         /* Don't send the ctx entry twice */
789                         if ( bvmatch( &a->a_nvals[0], srs->sr_state.ctxcsn ))
790                                 return LDAP_SUCCESS;
791                 }
792                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
793                         op->o_tmpmemctx );
794                 rs->sr_ctrls[1] = NULL;
795                 rs->sr_err = slap_build_sync_state_ctrl( op, rs, rs->sr_entry,
796                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
797         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
798                 struct berval cookie;
799
800                 slap_compose_sync_cookie( op, &cookie,
801                         &op->ors_filter->f_and->f_ava->aa_value,
802                         srs->sr_state.sid, srs->sr_state.rid );
803
804                 /* Is this a regular refresh? */
805                 if ( !ss->ss_so ) {
806                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
807                                 op->o_tmpmemctx );
808                         rs->sr_ctrls[1] = NULL;
809                         rs->sr_err = slap_build_sync_done_ctrl( op, rs, rs->sr_ctrls,
810                                 0, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
811                 } else {
812                         int locked = 0;
813                 /* It's RefreshAndPersist, transition to Persist phase */
814                         rs->sr_rspoid = LDAP_SYNC_INFO;
815                         slap_send_syncinfo( op, rs, rs->sr_nentries ?
816                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
817                                 &cookie, 1, NULL, 0 );
818                         /* Flush any queued persist messages */
819                         if ( ss->ss_so->s_res ) {
820                                 syncres *sr, *srnext;
821                                 Entry *e;
822                                 opcookie opc;
823
824                                 opc.son = on;
825                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
826                                 locked = 1;
827                                 for (sr = ss->ss_so->s_res; sr; sr=srnext) {
828                                         int rc = LDAP_SUCCESS;
829                                         srnext = sr->s_next;
830                                         opc.sdn = sr->s_dn;
831                                         opc.sndn = sr->s_ndn;
832                                         opc.suuid = sr->s_uuid;
833                                         opc.sctxcsn = sr->s_csn;
834                                         opc.sreference = sr->s_isreference;
835                                         e = NULL;
836                                         
837                                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
838                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
839                                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
840                                                 op->o_bd->bd_info = (BackendInfo *)on;
841                                         }
842                                         if ( rc == LDAP_SUCCESS )
843                                                 syncprov_sendresp( op, &opc, ss->ss_so, e,
844                                                         sr->s_mode, 0 );
845
846                                         if ( e ) {
847                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
848                                                 be_entry_release_r( op, e );
849                                                 op->o_bd->bd_info = (BackendInfo *)on;
850                                         }
851                                         ch_free( sr );
852                                 }
853                                 ss->ss_so->s_res = NULL;
854                                 ss->ss_so->s_restail = NULL;
855                         }
856
857                         /* Turn off the refreshing flag */
858                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
859                         if ( locked )
860                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
861
862                         /* Detach this Op from frontend control */
863                                 ss->ss_done = 1;
864                                 ;
865
866                         return LDAP_SUCCESS;
867                 }
868         }
869
870         return SLAP_CB_CONTINUE;
871 }
872
873 static int
874 syncprov_op_search( Operation *op, SlapReply *rs )
875 {
876         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
877         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
878         slap_callback   *cb;
879         int gotstate = 0, nochange = 0;
880         Filter *fand, *fava;
881         syncops *sop = NULL;
882         searchstate *ss;
883         syncrepl_state *srs;
884
885         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
886
887         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
888                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
889                 return rs->sr_err;
890         }
891
892         srs = op->o_controls[sync_cid];
893
894         /* If this is a persistent search, set it up right away */
895         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
896                 syncops so;
897                 fbase_cookie fc;
898                 opcookie opc;
899                 slap_callback sc;
900
901                 fc.fss = &so;
902                 fc.fbase = 0;
903                 so.s_eid = NOID;
904                 so.s_op = op;
905                 so.s_flags = PS_IS_REFRESHING;
906                 /* syncprov_findbase expects to be called as a callback... */
907                 sc.sc_private = &opc;
908                 opc.son = on;
909                 cb = op->o_callback;
910                 op->o_callback = &sc;
911                 rs->sr_err = syncprov_findbase( op, &fc );
912                 op->o_callback = cb;
913
914                 if ( rs->sr_err != LDAP_SUCCESS ) {
915                         send_ldap_result( op, rs );
916                         return rs->sr_err;
917                 }
918                 sop = ch_malloc( sizeof( syncops ));
919                 *sop = so;
920                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
921                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
922                 sop->s_next = si->si_ops;
923                 si->si_ops = sop;
924                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
925         }
926
927         /* If we have a cookie, handle the PRESENT lookups
928          */
929         if ( srs->sr_state.ctxcsn ) {
930                 /* Is the CSN in a valid format? */
931                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
932                         send_ldap_error( op, rs, LDAP_OTHER, "invalid sync cookie" );
933                         return rs->sr_err;
934                 }
935                 /* Is the CSN still present in the database? */
936                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
937                         /* No, so a reload is required */
938 #if 0           /* the consumer doesn't seem to send this hint */
939                         if ( op->o_sync_rhint == 0 ) {
940                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
941                                 return rs->sr_err;
942                         }
943 #endif
944                 } else {
945                         gotstate = 1;
946                         /* If just Refreshing and nothing has changed, shortcut it */
947                         if ( bvmatch( srs->sr_state.ctxcsn, &si->si_ctxcsn )) {
948                                 nochange = 1;
949                                 if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
950                                         LDAPControl     *ctrls[2];
951
952                                         ctrls[0] = NULL;
953                                         ctrls[1] = NULL;
954                                         slap_build_sync_done_ctrl( op, rs, ctrls, 0, 0,
955                                                 NULL, LDAP_SYNC_REFRESH_DELETES );
956                                         rs->sr_ctrls = ctrls;
957                                         rs->sr_err = LDAP_SUCCESS;
958                                         send_ldap_result( op, rs );
959                                         return rs->sr_err;
960                                 }
961                                 goto shortcut;
962                         } else 
963                         /* If context has changed, check for Present UUIDs */
964                         if ( syncprov_findcsn( op, FIND_PRESENT ) != LDAP_SUCCESS ) {
965                                 send_ldap_result( op, rs );
966                                 return rs->sr_err;
967                         }
968                 }
969         }
970
971         /* If we didn't get a cookie and we don't know our contextcsn, try to
972          * find it anyway.
973          */
974         if ( !gotstate && !si->si_gotcsn ) {
975                 struct berval bv = BER_BVC("1"), *old;
976                 
977                 old = srs->sr_state.ctxcsn;
978                 srs->sr_state.ctxcsn = &bv;
979                 syncprov_findcsn( op, FIND_CSN );
980                 srs->sr_state.ctxcsn = old;
981         }
982
983         /* Append CSN range to search filter, save original filter
984          * for persistent search evaluation
985          */
986         if ( sop ) {
987                 sop->s_filter = op->ors_filter;
988         }
989
990         fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
991         fand->f_choice = LDAP_FILTER_AND;
992         fand->f_next = NULL;
993         fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
994         fava->f_choice = LDAP_FILTER_LE;
995         fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
996         fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
997         ber_dupbv_x( &fava->f_ava->aa_value, &si->si_ctxcsn, op->o_tmpmemctx );
998         fand->f_and = fava;
999         if ( gotstate ) {
1000                 fava->f_next = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1001                 fava = fava->f_next;
1002                 fava->f_choice = LDAP_FILTER_GE;
1003                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1004                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1005                 ber_dupbv_x( &fava->f_ava->aa_value, srs->sr_state.ctxcsn, op->o_tmpmemctx );
1006         }
1007         fava->f_next = op->ors_filter;
1008         op->ors_filter = fand;
1009         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1010
1011 shortcut:
1012         /* Let our callback add needed info to returned entries */
1013         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1014         ss = (searchstate *)(cb+1);
1015         ss->ss_on = on;
1016         ss->ss_so = sop;
1017         ss->ss_done = 0;
1018         cb->sc_response = syncprov_search_response;
1019         cb->sc_cleanup = syncprov_search_cleanup;
1020         cb->sc_private = ss;
1021         cb->sc_next = op->o_callback;
1022         op->o_callback = cb;
1023
1024         /* FIXME: temporary hack to make sure back-bdb's native Psearch handling
1025          * doesn't get invoked. We can skip this after the back-bdb code is
1026          * removed, and also delete ss->ss_done.
1027          */
1028         op->o_sync_mode &= SLAP_CONTROL_MASK;
1029
1030         /* If this is a persistent search and no changes were reported during
1031          * the refresh phase, just invoke the response callback to transition
1032          * us into persist phase
1033          */
1034         if ( nochange ) {
1035                 rs->sr_err = LDAP_SUCCESS;
1036                 rs->sr_nentries = 0;
1037                 send_ldap_result( op, rs );
1038                 return rs->sr_err;
1039         }
1040         return SLAP_CB_CONTINUE;
1041 }
1042
1043 static int
1044 syncprov_db_config(
1045         BackendDB       *be,
1046         const char      *fname,
1047         int             lineno,
1048         int             argc,
1049         char    **argv
1050 )
1051 {
1052         slap_overinst           *on = (slap_overinst *)be->bd_info;
1053         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1054
1055 #if 0
1056         if ( strcasecmp( argv[ 0 ], "syncprov-checkpoint" ) == 0 ) {
1057                 if ( argc != 3 ) {
1058                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1059                                 "\"syncprov-checkpoint <ops> <minutes>\"\n", fname, lineno );
1060                         return -1;
1061                 }
1062                 si->si_chkops = atoi( argv[1] );
1063                 si->si_chktime = atoi( argv[2] ) * 60;
1064
1065         } else {
1066                 return SLAP_CONF_UNKNOWN;
1067         }
1068 #endif
1069
1070         return SLAP_CONF_UNKNOWN;
1071 }
1072
1073 static int
1074 syncprov_db_init(
1075         BackendDB *be
1076 )
1077 {
1078         slap_overinst   *on = (slap_overinst *)be->bd_info;
1079         syncprov_info_t *si;
1080
1081         si = ch_calloc(1, sizeof(syncprov_info_t));
1082         on->on_bi.bi_private = si;
1083         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
1084         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
1085         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
1086
1087         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
1088         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
1089
1090         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
1091         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1092
1093         sync_cid = slap_cids.sc_LDAPsync;
1094
1095         return 0;
1096 }
1097
1098 static int
1099 syncprov_db_destroy(
1100         BackendDB *be
1101 )
1102 {
1103         slap_overinst   *on = (slap_overinst *)be->bd_info;
1104         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1105
1106         if ( si ) {
1107                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
1108                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
1109                 ch_free( si );
1110         }
1111
1112         return 0;
1113 }
1114
1115 /* This overlay is set up for dynamic loading via moduleload. For static
1116  * configuration, you'll need to arrange for the slap_overinst to be
1117  * initialized and registered by some other function inside slapd.
1118  */
1119
1120 static slap_overinst            syncprov;
1121
1122 int
1123 syncprov_init()
1124 {
1125         syncprov.on_bi.bi_type = "syncprov";
1126         syncprov.on_bi.bi_db_init = syncprov_db_init;
1127         syncprov.on_bi.bi_db_config = syncprov_db_config;
1128         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
1129
1130         syncprov.on_bi.bi_op_add = syncprov_op_mod;
1131 #if 0
1132         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
1133 #endif
1134         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
1135         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
1136         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
1137         syncprov.on_bi.bi_op_search = syncprov_op_search;
1138         syncprov.on_bi.bi_extended = syncprov_op_extended;
1139
1140 #if 0
1141         syncprov.on_response = syncprov_response;
1142 #endif
1143
1144         return overlay_register( &syncprov );
1145 }
1146
1147 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
1148 int
1149 init_module( int argc, char *argv[] )
1150 {
1151         return syncprov_init();
1152 }
1153 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
1154
1155 #endif /* defined(SLAPD_OVER_SYNCPROV) */