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