]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
Added abandon/cancel support
[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         long    s_sid;
46         long    s_rid;
47         struct berval s_filterstr;
48         int             s_flags;        /* search status */
49         struct syncres *s_res;
50         struct syncres *s_restail;
51         ldap_pvt_thread_mutex_t s_mutex;
52 } syncops;
53
54 static int      sync_cid;
55
56 /* A received sync control */
57 typedef struct sync_control {
58         struct sync_cookie sr_state;
59         int sr_rhint;
60 } sync_control;
61
62 /* o_sync_mode uses data bits of o_sync */
63 #define o_sync  o_ctrlflag[sync_cid]
64 #define o_sync_mode     o_ctrlflag[sync_cid]
65
66 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
67 #define SLAP_SYNC_REFRESH                               (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
68 #define SLAP_SYNC_PERSIST                               (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
69 #define SLAP_SYNC_REFRESH_AND_PERSIST   (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
70
71 #define PS_IS_REFRESHING        0x01
72
73 /* Record of which searches matched at premodify step */
74 typedef struct syncmatches {
75         struct syncmatches *sm_next;
76         syncops *sm_op;
77 } syncmatches;
78
79 typedef struct syncprov_info_t {
80         syncops         *si_ops;
81         struct berval   si_ctxcsn;      /* ldapsync context */
82         int             si_gotcsn;      /* is our ctxcsn up to date? */
83         ldap_pvt_thread_mutex_t si_csn_mutex;
84         ldap_pvt_thread_mutex_t si_ops_mutex;
85         char            si_ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
86 } syncprov_info_t;
87
88 typedef struct opcookie {
89         slap_overinst *son;
90         syncmatches *smatches;
91         struct berval sdn;      /* DN of entry, for deletes */
92         struct berval sndn;
93         struct berval suuid;    /* UUID of entry */
94         struct berval sctxcsn;
95         int sreference; /* Is the entry a reference? */
96 } opcookie;
97
98 typedef struct fbase_cookie {
99         struct berval *fdn;     /* DN of a modified entry, for scope testing */
100         syncops *fss;   /* persistent search we're testing against */
101         int fbase;      /* if TRUE we found the search base and it's still valid */
102         int fscope;     /* if TRUE then fdn is within the psearch scope */
103 } fbase_cookie;
104
105 static AttributeName csn_anlist[2];
106 static AttributeName uuid_anlist[2];
107
108 static int
109 syncprov_state_ctrl(
110         Operation       *op,
111         SlapReply       *rs,
112         Entry           *e,
113         int                     entry_sync_state,
114         LDAPControl     **ctrls,
115         int                     num_ctrls,
116         int                     send_cookie,
117         struct berval   *cookie)
118 {
119         Attribute* a;
120         int ret;
121         int res;
122         const char *text = NULL;
123
124         BerElementBuffer berbuf;
125         BerElement *ber = (BerElement *)&berbuf;
126
127         struct berval entryuuid_bv      = BER_BVNULL;
128
129         ber_init2( ber, 0, LBER_USE_DER );
130         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
131
132         ctrls[num_ctrls] = slap_sl_malloc ( sizeof ( LDAPControl ), op->o_tmpmemctx );
133
134         for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
135                 AttributeDescription *desc = a->a_desc;
136                 if ( desc == slap_schema.si_ad_entryUUID ) {
137                         entryuuid_bv = a->a_nvals[0];
138                         break;
139                 }
140         }
141
142         if ( send_cookie && cookie ) {
143                 ber_printf( ber, "{eOON}",
144                         entry_sync_state, &entryuuid_bv, cookie );
145         } else {
146                 ber_printf( ber, "{eON}",
147                         entry_sync_state, &entryuuid_bv );
148         }
149
150         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
151         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
152         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
153
154         ber_free_buf( ber );
155
156         if ( ret < 0 ) {
157                 Debug( LDAP_DEBUG_TRACE,
158                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
159                         0, 0, 0 );
160                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
161                 return ret;
162         }
163
164         return LDAP_SUCCESS;
165 }
166
167 static int
168 syncprov_done_ctrl(
169         Operation       *op,
170         SlapReply       *rs,
171         LDAPControl     **ctrls,
172         int                     num_ctrls,
173         int                     send_cookie,
174         struct berval *cookie,
175         int                     refreshDeletes )
176 {
177         int ret;
178         BerElementBuffer berbuf;
179         BerElement *ber = (BerElement *)&berbuf;
180
181         ber_init2( ber, NULL, LBER_USE_DER );
182         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
183
184         ctrls[num_ctrls] = ch_malloc ( sizeof ( LDAPControl ) );
185
186         ber_printf( ber, "{" );
187         if ( send_cookie && cookie ) {
188                 ber_printf( ber, "O", cookie );
189         }
190         if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
191                 ber_printf( ber, "b", refreshDeletes );
192         }
193         ber_printf( ber, "N}" );        
194
195         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
196         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
197         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
198
199         ber_free_buf( ber );
200
201         if ( ret < 0 ) {
202                 Debug( LDAP_DEBUG_TRACE,
203                         "syncprov_done_ctrl: ber_flatten2 failed\n",
204                         0, 0, 0 );
205                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
206                 return ret;
207         }
208
209         return LDAP_SUCCESS;
210 }
211
212
213 static int
214 syncprov_state_ctrl_from_slog(
215         Operation       *op,
216         SlapReply       *rs,
217         struct slog_entry *slog_e,
218         int                     entry_sync_state,
219         LDAPControl     **ctrls,
220         int                     num_ctrls,
221         int                     send_cookie,
222         struct berval   *cookie)
223 {
224         Attribute* a;
225         int ret;
226         int res;
227         const char *text = NULL;
228
229         BerElementBuffer berbuf;
230         BerElement *ber = (BerElement *)&berbuf;
231
232         struct berval entryuuid_bv      = BER_BVNULL;
233
234         ber_init2( ber, NULL, LBER_USE_DER );
235         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
236
237         ctrls[num_ctrls] = ch_malloc ( sizeof ( LDAPControl ) );
238
239         entryuuid_bv = slog_e->sl_uuid;
240
241         if ( send_cookie && cookie ) {
242                 ber_printf( ber, "{eOON}",
243                         entry_sync_state, &entryuuid_bv, cookie );
244         } else {
245                 ber_printf( ber, "{eON}",
246                         entry_sync_state, &entryuuid_bv );
247         }
248
249         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
250         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
251         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
252
253         ber_free_buf( ber );
254
255         if ( ret < 0 ) {
256                 Debug( LDAP_DEBUG_TRACE,
257                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
258                         0, 0, 0 );
259                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
260                 return ret;
261         }
262
263         return LDAP_SUCCESS;
264 }
265
266 static int
267 syncprov_sendinfo(
268         Operation       *op,
269         SlapReply       *rs,
270         int                     type,
271         struct berval *cookie,
272         int                     refreshDone,
273         BerVarray       syncUUIDs,
274         int                     refreshDeletes )
275 {
276         BerElementBuffer berbuf;
277         BerElement *ber = (BerElement *)&berbuf;
278         struct berval rspdata;
279
280         int ret;
281
282         ber_init2( ber, NULL, LBER_USE_DER );
283         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
284
285         if ( type ) {
286                 switch ( type ) {
287                 case LDAP_TAG_SYNC_NEW_COOKIE:
288                         ber_printf( ber, "tO", type, cookie );
289                         break;
290                 case LDAP_TAG_SYNC_REFRESH_DELETE:
291                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
292                         ber_printf( ber, "t{", type );
293                         if ( cookie ) {
294                                 ber_printf( ber, "O", cookie );
295                         }
296                         if ( refreshDone == 0 ) {
297                                 ber_printf( ber, "b", refreshDone );
298                         }
299                         ber_printf( ber, "N}" );
300                         break;
301                 case LDAP_TAG_SYNC_ID_SET:
302                         ber_printf( ber, "t{", type );
303                         if ( cookie ) {
304                                 ber_printf( ber, "O", cookie );
305                         }
306                         if ( refreshDeletes == 1 ) {
307                                 ber_printf( ber, "b", refreshDeletes );
308                         }
309                         ber_printf( ber, "[W]", syncUUIDs );
310                         ber_printf( ber, "N}" );
311                         break;
312                 default:
313                         Debug( LDAP_DEBUG_TRACE,
314                                 "syncprov_sendinfo: invalid syncinfo type (%d)\n",
315                                 type, 0, 0 );
316                         return LDAP_OTHER;
317                 }
318         }
319
320         ret = ber_flatten2( ber, &rspdata, 0 );
321
322         if ( ret < 0 ) {
323                 Debug( LDAP_DEBUG_TRACE,
324                         "syncprov_sendinfo: ber_flatten2 failed\n",
325                         0, 0, 0 );
326                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
327                 return ret;
328         }
329
330         rs->sr_rspdata = &rspdata;
331         send_ldap_intermediate( op, rs );
332         rs->sr_rspdata = NULL;
333         ber_free_buf( ber );
334
335         return LDAP_SUCCESS;
336 }
337 /* syncprov_findbase:
338  *   finds the true DN of the base of a search (with alias dereferencing) and
339  * checks to make sure the base entry doesn't get replaced with a different
340  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
341  * change is detected, any persistent search on this base must be terminated /
342  * reloaded.
343  *   On the first call, we just save the DN and entryID. On subsequent calls
344  * we compare the DN and entryID with the saved values.
345  */
346 static int
347 findbase_cb( Operation *op, SlapReply *rs )
348 {
349         slap_callback *sc = op->o_callback;
350
351         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
352                 fbase_cookie *fc = sc->sc_private;
353
354                 /* If no entryID, we're looking for the first time.
355                  * Just store whatever we got.
356                  */
357                 if ( fc->fss->s_eid == NOID ) {
358                         fc->fbase = 1;
359                         fc->fss->s_eid = rs->sr_entry->e_id;
360                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
361
362                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
363                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
364
365                 /* OK, the DN is the same and the entryID is the same. Now
366                  * see if the fdn resides in the scope.
367                  */
368                         fc->fbase = 1;
369                         switch ( fc->fss->s_op->ors_scope ) {
370                         case LDAP_SCOPE_BASE:
371                                 fc->fscope = dn_match( fc->fdn, &rs->sr_entry->e_nname );
372                                 break;
373                         case LDAP_SCOPE_ONELEVEL: {
374                                 struct berval pdn;
375                                 dnParent( fc->fdn, &pdn );
376                                 fc->fscope = dn_match( &pdn, &rs->sr_entry->e_nname );
377                                 break; }
378                         case LDAP_SCOPE_SUBTREE:
379                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname );
380                                 break;
381 #ifdef LDAP_SCOPE_SUBORDINATE
382                         case LDAP_SCOPE_SUBORDINATE:
383                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname ) &&
384                                         !dn_match( fc->fdn, &rs->sr_entry->e_nname );
385                                 break;
386 #endif
387                         }
388                 }
389         }
390         return LDAP_SUCCESS;
391 }
392
393 static int
394 syncprov_findbase( Operation *op, fbase_cookie *fc )
395 {
396         opcookie *opc = op->o_callback->sc_private;
397         slap_overinst *on = opc->son;
398         syncprov_info_t         *si = on->on_bi.bi_private;
399
400         slap_callback cb = {0};
401         Operation fop;
402         SlapReply frs = { REP_RESULT };
403         int rc;
404
405         fop = *op;
406
407         cb.sc_response = findbase_cb;
408         cb.sc_private = fc;
409
410         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync mode */
411         fop.o_callback = &cb;
412         fop.o_tag = LDAP_REQ_SEARCH;
413         fop.ors_scope = LDAP_SCOPE_BASE;
414         fop.ors_deref = fc->fss->s_op->ors_deref;
415         fop.ors_slimit = 1;
416         fop.ors_tlimit = SLAP_NO_LIMIT;
417         fop.ors_attrs = slap_anlist_no_attrs;
418         fop.ors_attrsonly = 1;
419         fop.ors_filter = fc->fss->s_op->ors_filter;
420         fop.ors_filterstr = fc->fss->s_op->ors_filterstr;
421
422         fop.o_req_ndn = fc->fss->s_op->o_req_ndn;
423
424         fop.o_bd->bd_info = on->on_info->oi_orig;
425         rc = fop.o_bd->be_search( &fop, &frs );
426         fop.o_bd->bd_info = (BackendInfo *)on;
427
428         if ( fc->fbase ) return LDAP_SUCCESS;
429
430         /* If entryID has changed, then the base of this search has
431          * changed. Invalidate the psearch.
432          */
433         return LDAP_NO_SUCH_OBJECT;
434 }
435
436 /* syncprov_findcsn:
437  *   This function has three different purposes, but they all use a search
438  * that filters on entryCSN so they're combined here.
439  * 1: when the current contextCSN is unknown (i.e., at server start time)
440  * and a syncrepl search has arrived with a cookie, we search for all entries
441  * with CSN >= the cookie CSN, and store the maximum as our contextCSN. Also,
442  * we expect to find the cookie CSN in the search results, and note if we did
443  * or not. If not, we assume the cookie is stale. (This may be too restrictive,
444  * notice case 2.)
445  *
446  * 2: when the current contextCSN is known and we have a sync cookie, we search
447  * for one entry with CSN <= the cookie CSN. (Used to search for =.) If an
448  * entry is found, the cookie CSN is valid, otherwise it is stale. Case 1 is
449  * considered a special case of case 2, and both are generally called the
450  * "find CSN" task.
451  *
452  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
453  * CSN, and generate Present records for them. We always collect this result
454  * in SyncID sets, even if there's only one match.
455  */
456 #define FIND_CSN        1
457 #define FIND_PRESENT    2
458
459 typedef struct fcsn_cookie {
460         struct berval maxcsn;
461         int gotmatch;
462 } fcsn_cookie;
463
464 static int
465 findcsn_cb( Operation *op, SlapReply *rs )
466 {
467         slap_callback *sc = op->o_callback;
468
469         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
470                 /* If the private pointer is set, it points to an fcsn_cookie
471                  * and we want to record the maxcsn and match state.
472                  */
473                 if ( sc->sc_private ) {
474                         int i;
475                         fcsn_cookie *fc = sc->sc_private;
476                         sync_control *srs = op->o_controls[sync_cid];
477                         Attribute *a = attr_find(rs->sr_entry->e_attrs,
478                                 slap_schema.si_ad_entryCSN );
479                         i = ber_bvcmp( &a->a_vals[0], srs->sr_state.ctxcsn );
480                         if ( i == 0 ) fc->gotmatch = 1;
481                         i = ber_bvcmp( &a->a_vals[0], &fc->maxcsn );
482                         if ( i > 0 ) {
483                                 fc->maxcsn.bv_len = a->a_vals[0].bv_len;
484                                 strcpy(fc->maxcsn.bv_val, a->a_vals[0].bv_val );
485                         }
486                 } else {
487                 /* Otherwise, if the private pointer is not set, we just
488                  * want to know if any entry matched the filter.
489                  */
490                         sc->sc_private = (void *)1;
491                 }
492         }
493         return LDAP_SUCCESS;
494 }
495
496 /* Build a list of entryUUIDs for sending in a SyncID set */
497
498 typedef struct fpres_cookie {
499         int num;
500         BerVarray uuids;
501 } fpres_cookie;
502
503 static int
504 findpres_cb( Operation *op, SlapReply *rs )
505 {
506         slap_callback *sc = op->o_callback;
507         fpres_cookie *pc = sc->sc_private;
508         int ret = SLAP_CB_CONTINUE;
509
510         if ( rs->sr_type == REP_SEARCH ) {
511                 ret = slap_build_syncUUID_set( op, &pc->uuids, rs->sr_entry );
512                 if ( ret > 0 ) {
513                         pc->num++;
514                         ret = LDAP_SUCCESS;
515                         if ( pc->num == SLAP_SYNCUUID_SET_SIZE ) {
516                                 rs->sr_rspoid = LDAP_SYNC_INFO;
517                                 ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
518                                         0, pc->uuids, 0 );
519                                 ber_bvarray_free_x( pc->uuids, op->o_tmpmemctx );
520                                 pc->uuids = NULL;
521                                 pc->num = 0;
522                         }
523                 } else {
524                         ret = LDAP_OTHER;
525                 }
526         } else if ( rs->sr_type == REP_RESULT ) {
527                 ret = rs->sr_err;
528                 if ( pc->num ) {
529                         rs->sr_rspoid = LDAP_SYNC_INFO;
530                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
531                                 0, pc->uuids, 0 );
532                         ber_bvarray_free_x( pc->uuids, op->o_tmpmemctx );
533                         pc->uuids = NULL;
534                         pc->num = 0;
535                 }
536         }
537         return ret;
538 }
539
540
541 static int
542 syncprov_findcsn( Operation *op, int mode )
543 {
544         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
545         syncprov_info_t         *si = on->on_bi.bi_private;
546
547         slap_callback cb = {0};
548         Operation fop;
549         SlapReply frs = { REP_RESULT };
550         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
551         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
552         struct berval fbuf;
553         Filter cf;
554         AttributeAssertion eq;
555         int rc;
556         fcsn_cookie fcookie;
557         fpres_cookie pcookie;
558         int locked = 0;
559         sync_control *srs = op->o_controls[sync_cid];
560
561         if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
562                 return LDAP_OTHER;
563         }
564
565         fop = *op;
566         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
567
568         fbuf.bv_val = buf;
569         if ( mode == FIND_CSN ) {
570                 if ( !si->si_gotcsn ) {
571                         /* If we don't know the current ctxcsn, find it */
572                         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
573                         locked = 1;
574                 }
575                 if ( !si->si_gotcsn ) {
576                         cf.f_choice = LDAP_FILTER_GE;
577                         fop.ors_attrsonly = 0;
578                         fop.ors_attrs = csn_anlist;
579                         fop.ors_slimit = SLAP_NO_LIMIT;
580                         cb.sc_private = &fcookie;
581                         fcookie.maxcsn.bv_val = cbuf;
582                         fcookie.maxcsn.bv_len = 0;
583                         fcookie.gotmatch = 0;
584                         fbuf.bv_len = sprintf( buf, "(entryCSN>=%s)", srs->sr_state.ctxcsn->bv_val );
585                 } else {
586                         if ( locked ) {
587                                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
588                                 locked = 0;
589                         }
590                         cf.f_choice = LDAP_FILTER_LE;
591                         fop.ors_attrsonly = 1;
592                         fop.ors_attrs = slap_anlist_no_attrs;
593                         fop.ors_slimit = 1;
594                         cb.sc_private = NULL;
595                         fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)", srs->sr_state.ctxcsn->bv_val );
596                 }
597                 cb.sc_response = findcsn_cb;
598
599         } else if ( mode == FIND_PRESENT ) {
600                 cf.f_choice = LDAP_FILTER_LE;
601                 fop.ors_attrsonly = 0;
602                 fop.ors_attrs = uuid_anlist;
603                 fop.ors_slimit = SLAP_NO_LIMIT;
604                 /* We want pure entries, not referrals */
605                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
606                 cb.sc_private = &pcookie;
607                 cb.sc_response = findpres_cb;
608                 pcookie.num = 0;
609                 pcookie.uuids = NULL;
610                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)", srs->sr_state.ctxcsn->bv_val );
611         }
612         cf.f_ava = &eq;
613         cf.f_av_desc = slap_schema.si_ad_entryCSN;
614         cf.f_av_value = *srs->sr_state.ctxcsn;
615         cf.f_next = NULL;
616
617         fop.o_callback = &cb;
618         fop.ors_tlimit = SLAP_NO_LIMIT;
619         fop.ors_filter = &cf;
620         fop.ors_filterstr = fbuf;
621
622         fop.o_bd->bd_info = on->on_info->oi_orig;
623         rc = fop.o_bd->be_search( &fop, &frs );
624         fop.o_bd->bd_info = (BackendInfo *)on;
625
626         if ( mode == FIND_CSN ) {
627                 if ( !si->si_gotcsn ) {
628                         strcpy(si->si_ctxcsnbuf, fcookie.maxcsn.bv_val);
629                         si->si_ctxcsn.bv_len = fcookie.maxcsn.bv_len;
630                         si->si_gotcsn = 1;
631                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
632                         if ( fcookie.gotmatch ) return LDAP_SUCCESS;
633                         
634                 } else {
635                         if ( cb.sc_private ) return LDAP_SUCCESS;
636                 }
637         } else if ( mode == FIND_PRESENT ) {
638                 return LDAP_SUCCESS;
639         }
640
641         /* If matching CSN was not found, invalidate the context. */
642         return LDAP_NO_SUCH_OBJECT;
643 }
644
645 /* Queue a persistent search response if still in Refresh stage */
646 static int
647 syncprov_qresp( opcookie *opc, syncops *so, int mode )
648 {
649         syncres *sr;
650
651         sr = ch_malloc(sizeof(syncres) + opc->suuid.bv_len + 1 +
652                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1 + opc->sctxcsn.bv_len + 1 );
653         sr->s_next = NULL;
654         sr->s_dn.bv_val = (char *)(sr + 1);
655         sr->s_mode = mode;
656         sr->s_isreference = opc->sreference;
657         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val, opc->sdn.bv_val );
658         *(sr->s_ndn.bv_val++) = '\0';
659         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val, opc->sndn.bv_val );
660         *(sr->s_uuid.bv_val++) = '\0';
661         sr->s_csn.bv_val = lutil_strcopy( sr->s_uuid.bv_val, opc->suuid.bv_val );
662
663         if ( !so->s_res ) {
664                 so->s_res = sr;
665         } else {
666                 so->s_restail->s_next = sr;
667         }
668         so->s_restail = sr;
669         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
670         return LDAP_SUCCESS;
671 }
672
673 /* Send a persistent search response */
674 static int
675 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, Entry *e, int mode, int queue )
676 {
677         slap_overinst *on = opc->son;
678         syncprov_info_t *si = on->on_bi.bi_private;
679
680         SlapReply rs = { REP_SEARCH };
681         LDAPControl *ctrls[2];
682         struct berval cookie;
683         Entry e_uuid = {0};
684         Attribute a_uuid = {0};
685         Operation sop = *so->s_op;
686         Opheader ohdr;
687
688         ohdr = *sop.o_hdr;
689         sop.o_hdr = &ohdr;
690         sop.o_tmpmemctx = op->o_tmpmemctx;
691         sop.o_bd = op->o_bd;
692         sop.o_controls = op->o_controls;
693
694         if ( queue && (so->s_flags & PS_IS_REFRESHING) ) {
695                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
696                 if ( so->s_flags & PS_IS_REFRESHING )
697                         return syncprov_qresp( opc, so, mode );
698                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
699         }
700
701         ctrls[1] = NULL;
702         slap_compose_sync_cookie( op, &cookie, &opc->sctxcsn,
703                 so->s_sid, so->s_rid );
704
705         e_uuid.e_attrs = &a_uuid;
706         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
707         a_uuid.a_nvals = &opc->suuid;
708         rs.sr_err = syncprov_state_ctrl( &sop, &rs, &e_uuid,
709                 mode, ctrls, 0, 1, &cookie );
710
711         rs.sr_entry = e;
712         rs.sr_ctrls = ctrls;
713         switch( mode ) {
714         case LDAP_SYNC_ADD:
715                 if ( opc->sreference ) {
716                         rs.sr_ref = get_entry_referrals( &sop, e );
717                         send_search_reference( &sop, &rs );
718                         ber_bvarray_free( rs.sr_ref );
719                         break;
720                 }
721                 /* fallthru */
722         case LDAP_SYNC_MODIFY:
723                 rs.sr_attrs = sop.ors_attrs;
724                 send_search_entry( &sop, &rs );
725                 break;
726         case LDAP_SYNC_DELETE:
727                 e_uuid.e_attrs = NULL;
728                 e_uuid.e_name = opc->sdn;
729                 e_uuid.e_nname = opc->sndn;
730                 rs.sr_entry = &e_uuid;
731                 if ( opc->sreference ) {
732                         struct berval bv;
733                         bv.bv_val = NULL;
734                         bv.bv_len = 0;
735                         rs.sr_ref = &bv;
736                         send_search_reference( &sop, &rs );
737                 } else {
738                         send_search_entry( &sop, &rs );
739                 }
740                 break;
741         default:
742                 assert(0);
743         }
744         free( rs.sr_ctrls[0] );
745         return rs.sr_err;
746 }
747
748 static void
749 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
750 {
751         slap_overinst *on = opc->son;
752         syncprov_info_t         *si = on->on_bi.bi_private;
753
754         fbase_cookie fc;
755         syncops *ss;
756         Entry *e;
757         Attribute *a;
758         int rc;
759         struct berval newdn;
760
761         fc.fdn = &op->o_req_ndn;
762         /* compute new DN */
763         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
764                 struct berval pdn;
765                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
766                 else dnParent( fc.fdn, &pdn );
767                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
768                 fc.fdn = &newdn;
769         }
770         if ( op->o_tag != LDAP_REQ_ADD ) {
771                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
772                 rc = be_entry_get_rw( op, fc.fdn, NULL, NULL, 0, &e );
773                 op->o_bd->bd_info = (BackendInfo *)on;
774                 if ( rc ) return;
775         } else {
776                 e = op->ora_e;
777         }
778
779         if ( saveit ) {
780                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
781                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
782                 opc->sreference = is_entry_referral( e );
783         }
784         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
785                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
786                 if ( a )
787                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
788         }
789
790         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
791         for (ss = si->si_ops; ss; ss=ss->s_next)
792         {
793                 syncmatches *sm;
794                 int found = 0;
795
796                 /* validate base */
797                 fc.fss = ss;
798                 fc.fbase = 0;
799                 fc.fscope = 0;
800                 rc = syncprov_findbase( op, &fc );
801                 if ( rc != LDAP_SUCCESS ) continue;
802
803                 /* If we're sending results now, look for this op in old matches */
804                 if ( !saveit ) {
805                         syncmatches *old;
806                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
807                                 old=sm, sm=sm->sm_next ) {
808                                 if ( sm->sm_op == ss ) {
809                                         found = 1;
810                                         old->sm_next = sm->sm_next;
811                                         op->o_tmpfree( sm, op->o_tmpmemctx );
812                                         break;
813                                 }
814                         }
815                 }
816
817                 /* check if current o_req_dn is in scope and matches filter */
818                 if ( fc.fscope && test_filter( op, e, ss->s_op->ors_filter ) ==
819                         LDAP_COMPARE_TRUE ) {
820                         if ( saveit ) {
821                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
822                                 sm->sm_next = opc->smatches;
823                                 sm->sm_op = ss;
824                                 opc->smatches = sm;
825                         } else {
826                                 /* if found send UPDATE else send ADD */
827                                 syncprov_sendresp( op, opc, ss, e,
828                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD, 1 );
829                         }
830                 } else if ( !saveit && found ) {
831                         /* send DELETE */
832                         syncprov_sendresp( op, opc, ss, NULL, LDAP_SYNC_DELETE, 1 );
833                 }
834         }
835         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
836         if ( op->o_tag != LDAP_REQ_ADD ) {
837                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
838                 be_entry_release_r( op, e );
839                 op->o_bd->bd_info = (BackendInfo *)on;
840         }
841 }
842
843 static int
844 syncprov_op_cleanup( Operation *op, SlapReply *rs )
845 {
846         slap_callback *cb = op->o_callback;
847         opcookie *opc = cb->sc_private;
848         syncmatches *sm, *snext;
849
850         for (sm = opc->smatches; sm; sm=snext) {
851                 snext = sm->sm_next;
852                 op->o_tmpfree( sm, op->o_tmpmemctx );
853         }
854         op->o_callback = cb->sc_next;
855         op->o_tmpfree(cb, op->o_tmpmemctx);
856 }
857
858 static int
859 syncprov_op_response( Operation *op, SlapReply *rs )
860 {
861         opcookie *opc = op->o_callback->sc_private;
862         slap_overinst *on = opc->son;
863         syncprov_info_t         *si = on->on_bi.bi_private;
864         syncmatches *sm;
865
866         if ( rs->sr_err == LDAP_SUCCESS )
867         {
868                 struct berval maxcsn;
869                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
870
871                 cbuf[0] = '\0';
872                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
873                 slap_get_commit_csn( op, &maxcsn );
874                 if ( maxcsn.bv_val ) {
875                         strcpy( cbuf, maxcsn.bv_val );
876                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn ) > 0 ) {
877                                 strcpy( si->si_ctxcsnbuf, cbuf );
878                                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
879                         }
880                         si->si_gotcsn = 1;
881                 }
882                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
883
884                 opc->sctxcsn.bv_len = maxcsn.bv_len;
885                 opc->sctxcsn.bv_val = cbuf;
886
887                 if ( si->si_ops ) {
888                         switch(op->o_tag) {
889                         case LDAP_REQ_ADD:
890                         case LDAP_REQ_MODIFY:
891                         case LDAP_REQ_MODRDN:
892                         case LDAP_REQ_EXTENDED:
893                                 syncprov_matchops( op, opc, 0 );
894                                 break;
895                         case LDAP_REQ_DELETE:
896                                 /* for each match in opc->smatches:
897                                  *   send DELETE msg
898                                  */
899                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
900                                         syncprov_sendresp( op, opc, sm->sm_op, NULL,
901                                                 LDAP_SYNC_DELETE, 1 );
902                                 }
903                                 break;
904                         }
905                 }
906
907         }
908         return SLAP_CB_CONTINUE;
909 }
910
911 static void
912 syncprov_free_syncop( syncops *so )
913 {
914         syncres *sr, *srnext;
915
916         filter_free( so->s_op->ors_filter );
917         ch_free( so->s_op );
918         ch_free( so->s_base.bv_val );
919         for ( sr=so->s_res; sr; sr=srnext ) {
920                 srnext = sr->s_next;
921                 ch_free( sr );
922         }
923         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
924         ch_free( so );
925 }
926
927 static int
928 syncprov_op_abandon( Operation *op, SlapReply *rs )
929 {
930         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
931         syncprov_info_t         *si = on->on_bi.bi_private;
932         syncops *so, *soprev;
933
934         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
935         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
936                 soprev=so, so=so->s_next ) {
937                 if ( so->s_op->o_connid == op->o_connid &&
938                         so->s_op->o_msgid == op->orn_msgid ) {
939                                 soprev->s_next = so->s_next;
940                                 break;
941                 }
942         }
943         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
944         if ( so ) {
945                 ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
946                 op->o_conn->c_n_ops_executing--;
947                 op->o_conn->c_n_ops_completed++;
948                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
949                 /* Is this really a Cancel exop? */
950                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
951                         rs->sr_err = LDAP_CANCELLED;
952                         send_ldap_result( so->s_op, rs );
953                 }
954                 syncprov_free_syncop( so );
955         }
956         return SLAP_CB_CONTINUE;
957 }
958
959 #if 0
960 static int
961 syncprov_op_compare( Operation *op, SlapReply *rs )
962 {
963         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
964         syncprov_info_t         *si = on->on_bi.bi_private;
965         int rc = SLAP_CB_CONTINUE;
966
967         if ( dn_match( &op->o_req_ndn, &si->si_e->e_nname ) )
968         {
969                 Attribute *a;
970
971                 ldap_pvt_thread_mutex_lock( &si->si_e_mutex );
972
973                 if ( get_assert( op ) &&
974                         ( test_filter( op, si->si_e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
975                 {
976                         rs->sr_err = LDAP_ASSERTION_FAILED;
977                         goto return_results;
978                 }
979
980                 rs->sr_err = access_allowed( op, si->si_e, op->oq_compare.rs_ava->aa_desc,
981                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
982                 if ( ! rs->sr_err ) {
983                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
984                         goto return_results;
985                 }
986
987                 rs->sr_err = LDAP_NO_SUCH_ATTRIBUTE;
988
989                 for ( a = attr_find( si->si_e->e_attrs, op->oq_compare.rs_ava->aa_desc );
990                         a != NULL;
991                         a = attr_find( a->a_next, op->oq_compare.rs_ava->aa_desc ) )
992                 {
993                         rs->sr_err = LDAP_COMPARE_FALSE;
994
995                         if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
996                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
997                                         SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
998                                 a->a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
999                         {
1000                                 rs->sr_err = LDAP_COMPARE_TRUE;
1001                                 break;
1002                         }
1003                 }
1004
1005 return_results:;
1006
1007                 ldap_pvt_thread_mutex_unlock( &si->si_e_mutex );
1008
1009                 send_ldap_result( op, rs );
1010
1011                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1012                         rs->sr_err = LDAP_SUCCESS;
1013                 }
1014                 rc = rs->sr_err;
1015         }
1016
1017         return SLAP_CB_CONTINUE;
1018 }
1019 #endif
1020         
1021 static int
1022 syncprov_op_mod( Operation *op, SlapReply *rs )
1023 {
1024         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1025         syncprov_info_t         *si = on->on_bi.bi_private;
1026
1027         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(opcookie), op->o_tmpmemctx);
1028         opcookie *opc = (opcookie *)(cb+1);
1029         opc->son = on;
1030         cb->sc_response = syncprov_op_response;
1031         cb->sc_cleanup = syncprov_op_cleanup;
1032         cb->sc_private = opc;
1033         cb->sc_next = op->o_callback;
1034         op->o_callback = cb;
1035
1036         if ( si->si_ops && op->o_tag != LDAP_REQ_ADD )
1037                 syncprov_matchops( op, opc, 1 );
1038
1039         return SLAP_CB_CONTINUE;
1040 }
1041
1042 static int
1043 syncprov_op_extended( Operation *op, SlapReply *rs )
1044 {
1045         if ( exop_is_write( op ))
1046                 return syncprov_op_mod( op, rs );
1047
1048         return SLAP_CB_CONTINUE;
1049 }
1050
1051 typedef struct searchstate {
1052         slap_overinst *ss_on;
1053         syncops *ss_so;
1054 } searchstate;
1055
1056 static int
1057 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1058 {
1059         searchstate *ss = op->o_callback->sc_private;
1060         if ( rs->sr_ctrls ) {
1061                 free( rs->sr_ctrls[0] );
1062                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1063         }
1064         return 0;
1065 }
1066
1067 static void
1068 syncprov_detach_op( Operation *op, syncops *so )
1069 {
1070         Operation *op2;
1071         int i, alen = 0;
1072         size_t size;
1073         char *ptr;
1074
1075         /* count the search attrs */
1076         for (i=0; op->ors_attrs && op->ors_attrs[i].an_name.bv_val; i++) {
1077                 alen += op->ors_attrs[i].an_name.bv_len + 1;
1078         }
1079         /* Make a new copy of the operation */
1080         size = sizeof(Operation) + sizeof(Opheader) +
1081                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
1082                 op->o_req_dn.bv_len + 1 +
1083                 op->o_req_ndn.bv_len + 1 +
1084                 op->o_ndn.bv_len + 1 +
1085                 so->s_filterstr.bv_len + 1;
1086         op2 = (Operation *)ch_malloc( size );
1087         *op2 = *op;
1088         op2->o_hdr = (Opheader *)(op2+1);
1089         *op2->o_hdr = *op->o_hdr;
1090         if ( i ) {
1091                 op2->ors_attrs = (AttributeName *)(op2->o_hdr + 1);
1092                 ptr = (char *)(op2->ors_attrs+i+1);
1093                 for (i=0; op->ors_attrs[i].an_name.bv_val; i++) {
1094                         op2->ors_attrs[i] = op->ors_attrs[i];
1095                         op2->ors_attrs[i].an_name.bv_val = ptr;
1096                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
1097                 }
1098                 op2->ors_attrs[i].an_name.bv_val = NULL;
1099                 op2->ors_attrs[i].an_name.bv_len = 0;
1100         } else {
1101                 ptr = (char *)(op2->o_hdr + 1);
1102         }
1103         op2->o_ndn.bv_val = ptr;
1104         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
1105         op2->o_dn = op2->o_ndn;
1106         op2->o_req_dn.bv_val = ptr;
1107         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
1108         op2->o_req_ndn.bv_val = ptr;
1109         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
1110         op2->ors_filterstr.bv_val = ptr;
1111         strcpy( ptr, so->s_filterstr.bv_val );
1112         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
1113         op2->ors_filter = str2filter( ptr );
1114         op2->o_controls = NULL;
1115         op2->o_callback = NULL;
1116         so->s_op = op2;
1117
1118         /* Increment number of ops so that idletimeout ignores us */
1119         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1120         op->o_conn->c_n_ops_executing++;
1121         op->o_conn->c_n_ops_completed--;
1122         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1123 }
1124
1125 static int
1126 syncprov_search_response( Operation *op, SlapReply *rs )
1127 {
1128         searchstate *ss = op->o_callback->sc_private;
1129         slap_overinst *on = ss->ss_on;
1130         syncprov_info_t         *si = on->on_bi.bi_private;
1131         sync_control *srs = op->o_controls[sync_cid];
1132
1133         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
1134                 int i;
1135                 if ( srs->sr_state.ctxcsn ) {
1136                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
1137                                 slap_schema.si_ad_entryCSN );
1138                         /* Don't send the ctx entry twice */
1139                         if ( bvmatch( &a->a_nvals[0], srs->sr_state.ctxcsn ))
1140                                 return LDAP_SUCCESS;
1141                 }
1142                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1143                         op->o_tmpmemctx );
1144                 rs->sr_ctrls[1] = NULL;
1145                 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
1146                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
1147         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
1148                 struct berval cookie;
1149
1150                 slap_compose_sync_cookie( op, &cookie,
1151                         &op->ors_filter->f_and->f_ava->aa_value,
1152                         srs->sr_state.sid, srs->sr_state.rid );
1153
1154                 /* Is this a regular refresh? */
1155                 if ( !ss->ss_so ) {
1156                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1157                                 op->o_tmpmemctx );
1158                         rs->sr_ctrls[1] = NULL;
1159                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
1160                                 0, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
1161                 } else {
1162                         int locked = 0;
1163                 /* It's RefreshAndPersist, transition to Persist phase */
1164                         rs->sr_rspoid = LDAP_SYNC_INFO;
1165                         syncprov_sendinfo( op, rs, rs->sr_nentries ?
1166                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
1167                                 &cookie, 1, NULL, 0 );
1168                         /* Flush any queued persist messages */
1169                         if ( ss->ss_so->s_res ) {
1170                                 syncres *sr, *srnext;
1171                                 Entry *e;
1172                                 opcookie opc;
1173
1174                                 opc.son = on;
1175                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
1176                                 locked = 1;
1177                                 for (sr = ss->ss_so->s_res; sr; sr=srnext) {
1178                                         int rc = LDAP_SUCCESS;
1179                                         srnext = sr->s_next;
1180                                         opc.sdn = sr->s_dn;
1181                                         opc.sndn = sr->s_ndn;
1182                                         opc.suuid = sr->s_uuid;
1183                                         opc.sctxcsn = sr->s_csn;
1184                                         opc.sreference = sr->s_isreference;
1185                                         e = NULL;
1186                                         
1187                                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
1188                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1189                                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
1190                                                 op->o_bd->bd_info = (BackendInfo *)on;
1191                                         }
1192                                         if ( rc == LDAP_SUCCESS )
1193                                                 syncprov_sendresp( op, &opc, ss->ss_so, e,
1194                                                         sr->s_mode, 0 );
1195
1196                                         if ( e ) {
1197                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1198                                                 be_entry_release_r( op, e );
1199                                                 op->o_bd->bd_info = (BackendInfo *)on;
1200                                         }
1201                                         ch_free( sr );
1202                                 }
1203                                 ss->ss_so->s_res = NULL;
1204                                 ss->ss_so->s_restail = NULL;
1205                         }
1206
1207                         /* Turn off the refreshing flag */
1208                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
1209                         if ( locked )
1210                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
1211
1212                         /* Detach this Op from frontend control */
1213                         syncprov_detach_op( op, ss->ss_so );
1214
1215                         return LDAP_SUCCESS;
1216                 }
1217         }
1218
1219         return SLAP_CB_CONTINUE;
1220 }
1221
1222 static int
1223 syncprov_op_search( Operation *op, SlapReply *rs )
1224 {
1225         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1226         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1227         slap_callback   *cb;
1228         int gotstate = 0, nochange = 0;
1229         Filter *fand, *fava;
1230         syncops *sop = NULL;
1231         searchstate *ss;
1232         sync_control *srs;
1233
1234         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
1235
1236         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1237                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
1238                 return rs->sr_err;
1239         }
1240
1241         srs = op->o_controls[sync_cid];
1242
1243         /* If this is a persistent search, set it up right away */
1244         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
1245                 syncops so = {0};
1246                 fbase_cookie fc;
1247                 opcookie opc;
1248                 slap_callback sc;
1249
1250                 fc.fss = &so;
1251                 fc.fbase = 0;
1252                 so.s_eid = NOID;
1253                 so.s_op = op;
1254                 so.s_flags = PS_IS_REFRESHING;
1255                 /* syncprov_findbase expects to be called as a callback... */
1256                 sc.sc_private = &opc;
1257                 opc.son = on;
1258                 cb = op->o_callback;
1259                 op->o_callback = &sc;
1260                 rs->sr_err = syncprov_findbase( op, &fc );
1261                 op->o_callback = cb;
1262
1263                 if ( rs->sr_err != LDAP_SUCCESS ) {
1264                         send_ldap_result( op, rs );
1265                         return rs->sr_err;
1266                 }
1267                 sop = ch_malloc( sizeof( syncops ));
1268                 *sop = so;
1269                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
1270                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1271                 sop->s_sid = srs->sr_state.sid;
1272                 sop->s_rid = srs->sr_state.rid;
1273                 sop->s_next = si->si_ops;
1274                 si->si_ops = sop;
1275                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1276         }
1277
1278         /* If we have a cookie, handle the PRESENT lookups
1279          */
1280         if ( srs->sr_state.ctxcsn ) {
1281                 /* Is the CSN in a valid format? */
1282                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
1283                         send_ldap_error( op, rs, LDAP_OTHER, "invalid sync cookie" );
1284                         return rs->sr_err;
1285                 }
1286                 /* Is the CSN still present in the database? */
1287                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
1288                         /* No, so a reload is required */
1289 #if 0           /* the consumer doesn't seem to send this hint */
1290                         if ( op->o_sync_rhint == 0 ) {
1291                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
1292                                 return rs->sr_err;
1293                         }
1294 #endif
1295                 } else {
1296                         gotstate = 1;
1297                         /* If just Refreshing and nothing has changed, shortcut it */
1298                         if ( bvmatch( srs->sr_state.ctxcsn, &si->si_ctxcsn )) {
1299                                 nochange = 1;
1300                                 if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
1301                                         LDAPControl     *ctrls[2];
1302
1303                                         ctrls[0] = NULL;
1304                                         ctrls[1] = NULL;
1305                                         syncprov_done_ctrl( op, rs, ctrls, 0, 0,
1306                                                 NULL, LDAP_SYNC_REFRESH_DELETES );
1307                                         rs->sr_ctrls = ctrls;
1308                                         rs->sr_err = LDAP_SUCCESS;
1309                                         send_ldap_result( op, rs );
1310                                         return rs->sr_err;
1311                                 }
1312                                 goto shortcut;
1313                         } else 
1314                         /* If context has changed, check for Present UUIDs */
1315                         if ( syncprov_findcsn( op, FIND_PRESENT ) != LDAP_SUCCESS ) {
1316                                 send_ldap_result( op, rs );
1317                                 return rs->sr_err;
1318                         }
1319                 }
1320         }
1321
1322         /* If we didn't get a cookie and we don't know our contextcsn, try to
1323          * find it anyway.
1324          */
1325         if ( !gotstate && !si->si_gotcsn ) {
1326                 struct berval bv = BER_BVC("1"), *old;
1327                 
1328                 old = srs->sr_state.ctxcsn;
1329                 srs->sr_state.ctxcsn = &bv;
1330                 syncprov_findcsn( op, FIND_CSN );
1331                 srs->sr_state.ctxcsn = old;
1332         }
1333
1334         /* Append CSN range to search filter, save original filter
1335          * for persistent search evaluation
1336          */
1337         if ( sop ) {
1338                 sop->s_filterstr= op->ors_filterstr;
1339         }
1340
1341         fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1342         fand->f_choice = LDAP_FILTER_AND;
1343         fand->f_next = NULL;
1344         fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1345         fava->f_choice = LDAP_FILTER_LE;
1346         fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1347         fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1348         ber_dupbv_x( &fava->f_ava->aa_value, &si->si_ctxcsn, op->o_tmpmemctx );
1349         fand->f_and = fava;
1350         if ( gotstate ) {
1351                 fava->f_next = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1352                 fava = fava->f_next;
1353                 fava->f_choice = LDAP_FILTER_GE;
1354                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1355                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1356                 ber_dupbv_x( &fava->f_ava->aa_value, srs->sr_state.ctxcsn, op->o_tmpmemctx );
1357         }
1358         fava->f_next = op->ors_filter;
1359         op->ors_filter = fand;
1360         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1361
1362 shortcut:
1363         /* Let our callback add needed info to returned entries */
1364         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1365         ss = (searchstate *)(cb+1);
1366         ss->ss_on = on;
1367         ss->ss_so = sop;
1368         cb->sc_response = syncprov_search_response;
1369         cb->sc_cleanup = syncprov_search_cleanup;
1370         cb->sc_private = ss;
1371         cb->sc_next = op->o_callback;
1372         op->o_callback = cb;
1373
1374         op->o_sync_mode &= SLAP_CONTROL_MASK;
1375
1376         /* If this is a persistent search and no changes were reported during
1377          * the refresh phase, just invoke the response callback to transition
1378          * us into persist phase
1379          */
1380         if ( nochange ) {
1381                 rs->sr_err = LDAP_SUCCESS;
1382                 rs->sr_nentries = 0;
1383                 send_ldap_result( op, rs );
1384                 return rs->sr_err;
1385         }
1386         return SLAP_CB_CONTINUE;
1387 }
1388
1389 static int
1390 syncprov_db_config(
1391         BackendDB       *be,
1392         const char      *fname,
1393         int             lineno,
1394         int             argc,
1395         char    **argv
1396 )
1397 {
1398         slap_overinst           *on = (slap_overinst *)be->bd_info;
1399         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1400
1401 #if 0
1402         if ( strcasecmp( argv[ 0 ], "syncprov-checkpoint" ) == 0 ) {
1403                 if ( argc != 3 ) {
1404                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1405                                 "\"syncprov-checkpoint <ops> <minutes>\"\n", fname, lineno );
1406                         return -1;
1407                 }
1408                 si->si_chkops = atoi( argv[1] );
1409                 si->si_chktime = atoi( argv[2] ) * 60;
1410
1411         } else {
1412                 return SLAP_CONF_UNKNOWN;
1413         }
1414 #endif
1415
1416         return SLAP_CONF_UNKNOWN;
1417 }
1418
1419 static int
1420 syncprov_db_init(
1421         BackendDB *be
1422 )
1423 {
1424         slap_overinst   *on = (slap_overinst *)be->bd_info;
1425         syncprov_info_t *si;
1426
1427         si = ch_calloc(1, sizeof(syncprov_info_t));
1428         on->on_bi.bi_private = si;
1429         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
1430         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
1431         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
1432
1433         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
1434         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
1435
1436         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
1437         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1438
1439         return 0;
1440 }
1441
1442 static int
1443 syncprov_db_destroy(
1444         BackendDB *be
1445 )
1446 {
1447         slap_overinst   *on = (slap_overinst *)be->bd_info;
1448         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1449
1450         if ( si ) {
1451                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
1452                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
1453                 ch_free( si );
1454         }
1455
1456         return 0;
1457 }
1458
1459 static int syncprov_parseCtrl (
1460         Operation *op,
1461         SlapReply *rs,
1462         LDAPControl *ctrl )
1463 {
1464         ber_tag_t tag;
1465         BerElement *ber;
1466         ber_int_t mode;
1467         ber_len_t len;
1468         struct berval cookie = BER_BVNULL;
1469         sync_control *sr;
1470         int rhint = 0;
1471
1472         if ( op->o_sync != SLAP_CONTROL_NONE ) {
1473                 rs->sr_text = "Sync control specified multiple times";
1474                 return LDAP_PROTOCOL_ERROR;
1475         }
1476
1477         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
1478                 rs->sr_text = "Sync control specified with pagedResults control";
1479                 return LDAP_PROTOCOL_ERROR;
1480         }
1481
1482         if ( ctrl->ldctl_value.bv_len == 0 ) {
1483                 rs->sr_text = "Sync control value is empty (or absent)";
1484                 return LDAP_PROTOCOL_ERROR;
1485         }
1486
1487         /* Parse the control value
1488          *      syncRequestValue ::= SEQUENCE {
1489          *              mode   ENUMERATED {
1490          *                      -- 0 unused
1491          *                      refreshOnly             (1),
1492          *                      -- 2 reserved
1493          *                      refreshAndPersist       (3)
1494          *              },
1495          *              cookie  syncCookie OPTIONAL
1496          *      }
1497          */
1498
1499         ber = ber_init( &ctrl->ldctl_value );
1500         if( ber == NULL ) {
1501                 rs->sr_text = "internal error";
1502                 return LDAP_OTHER;
1503         }
1504
1505         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
1506                 rs->sr_text = "Sync control : mode decoding error";
1507                 return LDAP_PROTOCOL_ERROR;
1508         }
1509
1510         switch( mode ) {
1511         case LDAP_SYNC_REFRESH_ONLY:
1512                 mode = SLAP_SYNC_REFRESH;
1513                 break;
1514         case LDAP_SYNC_REFRESH_AND_PERSIST:
1515                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
1516                 break;
1517         default:
1518                 rs->sr_text = "Sync control : unknown update mode";
1519                 return LDAP_PROTOCOL_ERROR;
1520         }
1521
1522         tag = ber_peek_tag( ber, &len );
1523
1524         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
1525                 if (( ber_scanf( ber, /*{*/ "o", &cookie )) == LBER_ERROR ) {
1526                         rs->sr_text = "Sync control : cookie decoding error";
1527                         return LDAP_PROTOCOL_ERROR;
1528                 }
1529         }
1530         if ( tag == LDAP_TAG_RELOAD_HINT ) {
1531                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
1532                         rs->sr_text = "Sync control : rhint decoding error";
1533                         return LDAP_PROTOCOL_ERROR;
1534                 }
1535         }
1536         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
1537                         rs->sr_text = "Sync control : decoding error";
1538                         return LDAP_PROTOCOL_ERROR;
1539         }
1540         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
1541         sr->sr_rhint = rhint;
1542         if (!BER_BVISNULL(&cookie)) {
1543                 ber_bvarray_add( &sr->sr_state.octet_str, &cookie );
1544                 slap_parse_sync_cookie( &sr->sr_state );
1545         }
1546
1547         op->o_controls[sync_cid] = sr;
1548
1549         (void) ber_free( ber, 1 );
1550
1551         op->o_sync = ctrl->ldctl_iscritical
1552                 ? SLAP_CONTROL_CRITICAL
1553                 : SLAP_CONTROL_NONCRITICAL;
1554
1555         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
1556
1557         return LDAP_SUCCESS;
1558 }
1559
1560 /* This overlay is set up for dynamic loading via moduleload. For static
1561  * configuration, you'll need to arrange for the slap_overinst to be
1562  * initialized and registered by some other function inside slapd.
1563  */
1564
1565 static slap_overinst            syncprov;
1566
1567 int
1568 syncprov_init()
1569 {
1570         int rc;
1571
1572         rc = register_supported_control( LDAP_CONTROL_SYNC,
1573                 SLAP_CTRL_HIDE|SLAP_CTRL_SEARCH, NULL,
1574                 syncprov_parseCtrl, &sync_cid );
1575         if ( rc != LDAP_SUCCESS ) {
1576                 fprintf( stderr, "Failed to register control %d\n", rc );
1577                 return rc;
1578         }
1579
1580         syncprov.on_bi.bi_type = "syncprov";
1581         syncprov.on_bi.bi_db_init = syncprov_db_init;
1582         syncprov.on_bi.bi_db_config = syncprov_db_config;
1583         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
1584
1585         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
1586         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
1587
1588         syncprov.on_bi.bi_op_add = syncprov_op_mod;
1589 #if 0
1590         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
1591 #endif
1592         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
1593         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
1594         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
1595         syncprov.on_bi.bi_op_search = syncprov_op_search;
1596         syncprov.on_bi.bi_extended = syncprov_op_extended;
1597
1598 #if 0
1599         syncprov.on_response = syncprov_response;
1600 #endif
1601
1602         return overlay_register( &syncprov );
1603 }
1604
1605 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
1606 int
1607 init_module( int argc, char *argv[] )
1608 {
1609         return syncprov_init();
1610 }
1611 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
1612
1613 #endif /* defined(SLAPD_OVER_SYNCPROV) */