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