]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
ca36a7b560d0892543b533dcf51af8e435941d67
[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 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 #if 0
912 static int
913 syncprov_op_compare( Operation *op, SlapReply *rs )
914 {
915         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
916         syncprov_info_t         *si = on->on_bi.bi_private;
917         int rc = SLAP_CB_CONTINUE;
918
919         if ( dn_match( &op->o_req_ndn, &si->si_e->e_nname ) )
920         {
921                 Attribute *a;
922
923                 ldap_pvt_thread_mutex_lock( &si->si_e_mutex );
924
925                 if ( get_assert( op ) &&
926                         ( test_filter( op, si->si_e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
927                 {
928                         rs->sr_err = LDAP_ASSERTION_FAILED;
929                         goto return_results;
930                 }
931
932                 rs->sr_err = access_allowed( op, si->si_e, op->oq_compare.rs_ava->aa_desc,
933                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
934                 if ( ! rs->sr_err ) {
935                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
936                         goto return_results;
937                 }
938
939                 rs->sr_err = LDAP_NO_SUCH_ATTRIBUTE;
940
941                 for ( a = attr_find( si->si_e->e_attrs, op->oq_compare.rs_ava->aa_desc );
942                         a != NULL;
943                         a = attr_find( a->a_next, op->oq_compare.rs_ava->aa_desc ) )
944                 {
945                         rs->sr_err = LDAP_COMPARE_FALSE;
946
947                         if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
948                                 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
949                                         SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
950                                 a->a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
951                         {
952                                 rs->sr_err = LDAP_COMPARE_TRUE;
953                                 break;
954                         }
955                 }
956
957 return_results:;
958
959                 ldap_pvt_thread_mutex_unlock( &si->si_e_mutex );
960
961                 send_ldap_result( op, rs );
962
963                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
964                         rs->sr_err = LDAP_SUCCESS;
965                 }
966                 rc = rs->sr_err;
967         }
968
969         return SLAP_CB_CONTINUE;
970 }
971 #endif
972         
973 static int
974 syncprov_op_mod( Operation *op, SlapReply *rs )
975 {
976         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
977         syncprov_info_t         *si = on->on_bi.bi_private;
978
979         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(opcookie), op->o_tmpmemctx);
980         opcookie *opc = (opcookie *)(cb+1);
981         opc->son = on;
982         cb->sc_response = syncprov_op_response;
983         cb->sc_cleanup = syncprov_op_cleanup;
984         cb->sc_private = opc;
985         cb->sc_next = op->o_callback;
986         op->o_callback = cb;
987
988         if ( si->si_ops && op->o_tag != LDAP_REQ_ADD )
989                 syncprov_matchops( op, opc, 1 );
990
991         return SLAP_CB_CONTINUE;
992 }
993
994 static int
995 syncprov_op_extended( Operation *op, SlapReply *rs )
996 {
997         if ( exop_is_write( op ))
998                 return syncprov_op_mod( op, rs );
999
1000         return SLAP_CB_CONTINUE;
1001 }
1002
1003 typedef struct searchstate {
1004         slap_overinst *ss_on;
1005         syncops *ss_so;
1006 } searchstate;
1007
1008 static int
1009 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1010 {
1011         searchstate *ss = op->o_callback->sc_private;
1012         if ( rs->sr_ctrls ) {
1013                 free( rs->sr_ctrls[0] );
1014                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1015         }
1016         return 0;
1017 }
1018
1019 static void
1020 syncprov_detach_op( Operation *op, syncops *so )
1021 {
1022         Operation *op2;
1023         int i, alen = 0;
1024         size_t size;
1025         char *ptr;
1026
1027         /* count the search attrs */
1028         for (i=0; op->ors_attrs && op->ors_attrs[i].an_name.bv_val; i++) {
1029                 alen += op->ors_attrs[i].an_name.bv_len + 1;
1030         }
1031         /* Make a new copy of the operation */
1032         size = sizeof(Operation) + sizeof(Opheader) +
1033                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
1034                 op->o_req_dn.bv_len + 1 +
1035                 op->o_req_ndn.bv_len + 1 +
1036                 op->o_ndn.bv_len + 1 +
1037                 so->s_filterstr.bv_len + 1;
1038         op2 = (Operation *)ch_malloc( size );
1039         *op2 = *op;
1040         op2->o_hdr = (Opheader *)(op2+1);
1041         *op2->o_hdr = *op->o_hdr;
1042         if ( i ) {
1043                 op2->ors_attrs = (AttributeName *)(op2->o_hdr + 1);
1044                 ptr = (char *)(op2->ors_attrs+i+1);
1045                 for (i=0; op->ors_attrs[i].an_name.bv_val; i++) {
1046                         op2->ors_attrs[i] = op->ors_attrs[i];
1047                         op2->ors_attrs[i].an_name.bv_val = ptr;
1048                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
1049                 }
1050                 op2->ors_attrs[i].an_name.bv_val = NULL;
1051                 op2->ors_attrs[i].an_name.bv_len = 0;
1052         } else {
1053                 ptr = (char *)(op2->o_hdr + 1);
1054         }
1055         op2->o_ndn.bv_val = ptr;
1056         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
1057         op2->o_dn = op2->o_ndn;
1058         op2->o_req_dn.bv_val = ptr;
1059         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
1060         op2->o_req_ndn.bv_val = ptr;
1061         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
1062         op2->ors_filterstr.bv_val = ptr;
1063         strcpy( ptr, so->s_filterstr.bv_val );
1064         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
1065         op2->ors_filter = str2filter( ptr );
1066         op2->o_controls = NULL;
1067         op2->o_callback = NULL;
1068         so->s_op = op2;
1069
1070         /* Increment number of ops so that idletimeout ignores us */
1071         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1072         op->o_conn->c_n_ops_executing++;
1073         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1074 }
1075
1076 static int
1077 syncprov_search_response( Operation *op, SlapReply *rs )
1078 {
1079         searchstate *ss = op->o_callback->sc_private;
1080         slap_overinst *on = ss->ss_on;
1081         syncprov_info_t         *si = on->on_bi.bi_private;
1082         sync_control *srs = op->o_controls[sync_cid];
1083
1084         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
1085                 int i;
1086                 if ( srs->sr_state.ctxcsn ) {
1087                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
1088                                 slap_schema.si_ad_entryCSN );
1089                         /* Don't send the ctx entry twice */
1090                         if ( bvmatch( &a->a_nvals[0], srs->sr_state.ctxcsn ))
1091                                 return LDAP_SUCCESS;
1092                 }
1093                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1094                         op->o_tmpmemctx );
1095                 rs->sr_ctrls[1] = NULL;
1096                 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
1097                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
1098         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
1099                 struct berval cookie;
1100
1101                 slap_compose_sync_cookie( op, &cookie,
1102                         &op->ors_filter->f_and->f_ava->aa_value,
1103                         srs->sr_state.sid, srs->sr_state.rid );
1104
1105                 /* Is this a regular refresh? */
1106                 if ( !ss->ss_so ) {
1107                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1108                                 op->o_tmpmemctx );
1109                         rs->sr_ctrls[1] = NULL;
1110                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
1111                                 0, 1, &cookie, LDAP_SYNC_REFRESH_PRESENTS );
1112                 } else {
1113                         int locked = 0;
1114                 /* It's RefreshAndPersist, transition to Persist phase */
1115                         rs->sr_rspoid = LDAP_SYNC_INFO;
1116                         syncprov_sendinfo( op, rs, rs->sr_nentries ?
1117                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
1118                                 &cookie, 1, NULL, 0 );
1119                         /* Flush any queued persist messages */
1120                         if ( ss->ss_so->s_res ) {
1121                                 syncres *sr, *srnext;
1122                                 Entry *e;
1123                                 opcookie opc;
1124
1125                                 opc.son = on;
1126                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
1127                                 locked = 1;
1128                                 for (sr = ss->ss_so->s_res; sr; sr=srnext) {
1129                                         int rc = LDAP_SUCCESS;
1130                                         srnext = sr->s_next;
1131                                         opc.sdn = sr->s_dn;
1132                                         opc.sndn = sr->s_ndn;
1133                                         opc.suuid = sr->s_uuid;
1134                                         opc.sctxcsn = sr->s_csn;
1135                                         opc.sreference = sr->s_isreference;
1136                                         e = NULL;
1137                                         
1138                                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
1139                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1140                                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
1141                                                 op->o_bd->bd_info = (BackendInfo *)on;
1142                                         }
1143                                         if ( rc == LDAP_SUCCESS )
1144                                                 syncprov_sendresp( op, &opc, ss->ss_so, e,
1145                                                         sr->s_mode, 0 );
1146
1147                                         if ( e ) {
1148                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1149                                                 be_entry_release_r( op, e );
1150                                                 op->o_bd->bd_info = (BackendInfo *)on;
1151                                         }
1152                                         ch_free( sr );
1153                                 }
1154                                 ss->ss_so->s_res = NULL;
1155                                 ss->ss_so->s_restail = NULL;
1156                         }
1157
1158                         /* Turn off the refreshing flag */
1159                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
1160                         if ( locked )
1161                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
1162
1163                         /* Detach this Op from frontend control */
1164                         syncprov_detach_op( op, ss->ss_so );
1165
1166                         return LDAP_SUCCESS;
1167                 }
1168         }
1169
1170         return SLAP_CB_CONTINUE;
1171 }
1172
1173 static int
1174 syncprov_op_search( Operation *op, SlapReply *rs )
1175 {
1176         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1177         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1178         slap_callback   *cb;
1179         int gotstate = 0, nochange = 0;
1180         Filter *fand, *fava;
1181         syncops *sop = NULL;
1182         searchstate *ss;
1183         sync_control *srs;
1184
1185         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
1186
1187         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1188                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
1189                 return rs->sr_err;
1190         }
1191
1192         srs = op->o_controls[sync_cid];
1193
1194         /* If this is a persistent search, set it up right away */
1195         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
1196                 syncops so = {0};
1197                 fbase_cookie fc;
1198                 opcookie opc;
1199                 slap_callback sc;
1200
1201                 fc.fss = &so;
1202                 fc.fbase = 0;
1203                 so.s_eid = NOID;
1204                 so.s_op = op;
1205                 so.s_flags = PS_IS_REFRESHING;
1206                 /* syncprov_findbase expects to be called as a callback... */
1207                 sc.sc_private = &opc;
1208                 opc.son = on;
1209                 cb = op->o_callback;
1210                 op->o_callback = &sc;
1211                 rs->sr_err = syncprov_findbase( op, &fc );
1212                 op->o_callback = cb;
1213
1214                 if ( rs->sr_err != LDAP_SUCCESS ) {
1215                         send_ldap_result( op, rs );
1216                         return rs->sr_err;
1217                 }
1218                 sop = ch_malloc( sizeof( syncops ));
1219                 *sop = so;
1220                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
1221                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1222                 sop->s_sid = srs->sr_state.sid;
1223                 sop->s_rid = srs->sr_state.rid;
1224                 sop->s_next = si->si_ops;
1225                 si->si_ops = sop;
1226                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1227         }
1228
1229         /* If we have a cookie, handle the PRESENT lookups
1230          */
1231         if ( srs->sr_state.ctxcsn ) {
1232                 /* Is the CSN in a valid format? */
1233                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
1234                         send_ldap_error( op, rs, LDAP_OTHER, "invalid sync cookie" );
1235                         return rs->sr_err;
1236                 }
1237                 /* Is the CSN still present in the database? */
1238                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
1239                         /* No, so a reload is required */
1240 #if 0           /* the consumer doesn't seem to send this hint */
1241                         if ( op->o_sync_rhint == 0 ) {
1242                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
1243                                 return rs->sr_err;
1244                         }
1245 #endif
1246                 } else {
1247                         gotstate = 1;
1248                         /* If just Refreshing and nothing has changed, shortcut it */
1249                         if ( bvmatch( srs->sr_state.ctxcsn, &si->si_ctxcsn )) {
1250                                 nochange = 1;
1251                                 if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
1252                                         LDAPControl     *ctrls[2];
1253
1254                                         ctrls[0] = NULL;
1255                                         ctrls[1] = NULL;
1256                                         syncprov_done_ctrl( op, rs, ctrls, 0, 0,
1257                                                 NULL, LDAP_SYNC_REFRESH_DELETES );
1258                                         rs->sr_ctrls = ctrls;
1259                                         rs->sr_err = LDAP_SUCCESS;
1260                                         send_ldap_result( op, rs );
1261                                         return rs->sr_err;
1262                                 }
1263                                 goto shortcut;
1264                         } else 
1265                         /* If context has changed, check for Present UUIDs */
1266                         if ( syncprov_findcsn( op, FIND_PRESENT ) != LDAP_SUCCESS ) {
1267                                 send_ldap_result( op, rs );
1268                                 return rs->sr_err;
1269                         }
1270                 }
1271         }
1272
1273         /* If we didn't get a cookie and we don't know our contextcsn, try to
1274          * find it anyway.
1275          */
1276         if ( !gotstate && !si->si_gotcsn ) {
1277                 struct berval bv = BER_BVC("1"), *old;
1278                 
1279                 old = srs->sr_state.ctxcsn;
1280                 srs->sr_state.ctxcsn = &bv;
1281                 syncprov_findcsn( op, FIND_CSN );
1282                 srs->sr_state.ctxcsn = old;
1283         }
1284
1285         /* Append CSN range to search filter, save original filter
1286          * for persistent search evaluation
1287          */
1288         if ( sop ) {
1289                 sop->s_filterstr= op->ors_filterstr;
1290         }
1291
1292         fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1293         fand->f_choice = LDAP_FILTER_AND;
1294         fand->f_next = NULL;
1295         fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1296         fava->f_choice = LDAP_FILTER_LE;
1297         fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1298         fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1299         ber_dupbv_x( &fava->f_ava->aa_value, &si->si_ctxcsn, op->o_tmpmemctx );
1300         fand->f_and = fava;
1301         if ( gotstate ) {
1302                 fava->f_next = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1303                 fava = fava->f_next;
1304                 fava->f_choice = LDAP_FILTER_GE;
1305                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1306                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1307                 ber_dupbv_x( &fava->f_ava->aa_value, srs->sr_state.ctxcsn, op->o_tmpmemctx );
1308         }
1309         fava->f_next = op->ors_filter;
1310         op->ors_filter = fand;
1311         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1312
1313 shortcut:
1314         /* Let our callback add needed info to returned entries */
1315         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1316         ss = (searchstate *)(cb+1);
1317         ss->ss_on = on;
1318         ss->ss_so = sop;
1319         cb->sc_response = syncprov_search_response;
1320         cb->sc_cleanup = syncprov_search_cleanup;
1321         cb->sc_private = ss;
1322         cb->sc_next = op->o_callback;
1323         op->o_callback = cb;
1324
1325         op->o_sync_mode &= SLAP_CONTROL_MASK;
1326
1327         /* If this is a persistent search and no changes were reported during
1328          * the refresh phase, just invoke the response callback to transition
1329          * us into persist phase
1330          */
1331         if ( nochange ) {
1332                 rs->sr_err = LDAP_SUCCESS;
1333                 rs->sr_nentries = 0;
1334                 send_ldap_result( op, rs );
1335                 return rs->sr_err;
1336         }
1337         return SLAP_CB_CONTINUE;
1338 }
1339
1340 static int
1341 syncprov_db_config(
1342         BackendDB       *be,
1343         const char      *fname,
1344         int             lineno,
1345         int             argc,
1346         char    **argv
1347 )
1348 {
1349         slap_overinst           *on = (slap_overinst *)be->bd_info;
1350         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1351
1352 #if 0
1353         if ( strcasecmp( argv[ 0 ], "syncprov-checkpoint" ) == 0 ) {
1354                 if ( argc != 3 ) {
1355                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1356                                 "\"syncprov-checkpoint <ops> <minutes>\"\n", fname, lineno );
1357                         return -1;
1358                 }
1359                 si->si_chkops = atoi( argv[1] );
1360                 si->si_chktime = atoi( argv[2] ) * 60;
1361
1362         } else {
1363                 return SLAP_CONF_UNKNOWN;
1364         }
1365 #endif
1366
1367         return SLAP_CONF_UNKNOWN;
1368 }
1369
1370 static int
1371 syncprov_db_init(
1372         BackendDB *be
1373 )
1374 {
1375         slap_overinst   *on = (slap_overinst *)be->bd_info;
1376         syncprov_info_t *si;
1377
1378         si = ch_calloc(1, sizeof(syncprov_info_t));
1379         on->on_bi.bi_private = si;
1380         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
1381         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
1382         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
1383
1384         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
1385         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
1386
1387         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
1388         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1389
1390         return 0;
1391 }
1392
1393 static int
1394 syncprov_db_destroy(
1395         BackendDB *be
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 ( si ) {
1402                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
1403                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
1404                 ch_free( si );
1405         }
1406
1407         return 0;
1408 }
1409
1410 static int syncprov_parseCtrl (
1411         Operation *op,
1412         SlapReply *rs,
1413         LDAPControl *ctrl )
1414 {
1415         ber_tag_t tag;
1416         BerElement *ber;
1417         ber_int_t mode;
1418         ber_len_t len;
1419         struct berval cookie = BER_BVNULL;
1420         sync_control *sr;
1421         int rhint = 0;
1422
1423         if ( op->o_sync != SLAP_CONTROL_NONE ) {
1424                 rs->sr_text = "Sync control specified multiple times";
1425                 return LDAP_PROTOCOL_ERROR;
1426         }
1427
1428         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
1429                 rs->sr_text = "Sync control specified with pagedResults control";
1430                 return LDAP_PROTOCOL_ERROR;
1431         }
1432
1433         if ( ctrl->ldctl_value.bv_len == 0 ) {
1434                 rs->sr_text = "Sync control value is empty (or absent)";
1435                 return LDAP_PROTOCOL_ERROR;
1436         }
1437
1438         /* Parse the control value
1439          *      syncRequestValue ::= SEQUENCE {
1440          *              mode   ENUMERATED {
1441          *                      -- 0 unused
1442          *                      refreshOnly             (1),
1443          *                      -- 2 reserved
1444          *                      refreshAndPersist       (3)
1445          *              },
1446          *              cookie  syncCookie OPTIONAL
1447          *      }
1448          */
1449
1450         ber = ber_init( &ctrl->ldctl_value );
1451         if( ber == NULL ) {
1452                 rs->sr_text = "internal error";
1453                 return LDAP_OTHER;
1454         }
1455
1456         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
1457                 rs->sr_text = "Sync control : mode decoding error";
1458                 return LDAP_PROTOCOL_ERROR;
1459         }
1460
1461         switch( mode ) {
1462         case LDAP_SYNC_REFRESH_ONLY:
1463                 mode = SLAP_SYNC_REFRESH;
1464                 break;
1465         case LDAP_SYNC_REFRESH_AND_PERSIST:
1466                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
1467                 break;
1468         default:
1469                 rs->sr_text = "Sync control : unknown update mode";
1470                 return LDAP_PROTOCOL_ERROR;
1471         }
1472
1473         tag = ber_peek_tag( ber, &len );
1474
1475         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
1476                 if (( ber_scanf( ber, /*{*/ "o", &cookie )) == LBER_ERROR ) {
1477                         rs->sr_text = "Sync control : cookie decoding error";
1478                         return LDAP_PROTOCOL_ERROR;
1479                 }
1480         }
1481         if ( tag == LDAP_TAG_RELOAD_HINT ) {
1482                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
1483                         rs->sr_text = "Sync control : rhint decoding error";
1484                         return LDAP_PROTOCOL_ERROR;
1485                 }
1486         }
1487         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
1488                         rs->sr_text = "Sync control : decoding error";
1489                         return LDAP_PROTOCOL_ERROR;
1490         }
1491         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
1492         sr->sr_rhint = rhint;
1493         if (!BER_BVISNULL(&cookie)) {
1494                 ber_bvarray_add( &sr->sr_state.octet_str, &cookie );
1495                 slap_parse_sync_cookie( &sr->sr_state );
1496         }
1497
1498         op->o_controls[sync_cid] = sr;
1499
1500         (void) ber_free( ber, 1 );
1501
1502         op->o_sync = ctrl->ldctl_iscritical
1503                 ? SLAP_CONTROL_CRITICAL
1504                 : SLAP_CONTROL_NONCRITICAL;
1505
1506         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
1507
1508         return LDAP_SUCCESS;
1509 }
1510
1511 /* This overlay is set up for dynamic loading via moduleload. For static
1512  * configuration, you'll need to arrange for the slap_overinst to be
1513  * initialized and registered by some other function inside slapd.
1514  */
1515
1516 static slap_overinst            syncprov;
1517
1518 int
1519 syncprov_init()
1520 {
1521         int rc;
1522
1523         rc = register_supported_control( LDAP_CONTROL_SYNC,
1524                 SLAP_CTRL_HIDE|SLAP_CTRL_SEARCH, NULL,
1525                 syncprov_parseCtrl, &sync_cid );
1526         if ( rc != LDAP_SUCCESS ) {
1527                 fprintf( stderr, "Failed to register control %d\n", rc );
1528                 return rc;
1529         }
1530
1531         syncprov.on_bi.bi_type = "syncprov";
1532         syncprov.on_bi.bi_db_init = syncprov_db_init;
1533         syncprov.on_bi.bi_db_config = syncprov_db_config;
1534         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
1535
1536         syncprov.on_bi.bi_op_add = syncprov_op_mod;
1537 #if 0
1538         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
1539 #endif
1540         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
1541         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
1542         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
1543         syncprov.on_bi.bi_op_search = syncprov_op_search;
1544         syncprov.on_bi.bi_extended = syncprov_op_extended;
1545
1546 #if 0
1547         syncprov.on_response = syncprov_response;
1548 #endif
1549
1550         return overlay_register( &syncprov );
1551 }
1552
1553 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
1554 int
1555 init_module( int argc, char *argv[] )
1556 {
1557         return syncprov_init();
1558 }
1559 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
1560
1561 #endif /* defined(SLAPD_OVER_SYNCPROV) */