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