]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
Fix prev commit
[openldap] / servers / slapd / overlays / syncprov.c
1 /* $OpenLDAP$ */
2 /* syncprov.c - syncrepl provider */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2004-2005 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS:
17  * This work was initially developed by Howard Chu for inclusion in
18  * OpenLDAP Software.
19  */
20
21 #include "portable.h"
22
23 #ifdef SLAPD_OVER_SYNCPROV
24
25 #include <ac/string.h>
26 #include "lutil.h"
27 #include "slap.h"
28
29 /* A modify request on a particular entry */
30 typedef struct modinst {
31         struct modinst *mi_next;
32         Operation *mi_op;
33 } modinst;
34
35 typedef struct modtarget {
36         struct modinst *mt_mods;
37         struct modinst *mt_tail;
38         Operation *mt_op;
39         ldap_pvt_thread_mutex_t mt_mutex;
40 } modtarget;
41
42 /* A queued result of a persistent search */
43 typedef struct syncres {
44         struct syncres *s_next;
45         struct berval s_dn;
46         struct berval s_ndn;
47         struct berval s_uuid;
48         struct berval s_csn;
49         char s_mode;
50         char s_isreference;
51 } syncres;
52
53 /* Record of a persistent search */
54 typedef struct syncops {
55         struct syncops *s_next;
56         struct berval   s_base;         /* ndn of search base */
57         ID              s_eid;          /* entryID of search base */
58         Operation       *s_op;          /* search op */
59         int             s_rid;
60         struct berval s_filterstr;
61         int             s_flags;        /* search status */
62         int             s_inuse;        /* reference count */
63         struct syncres *s_res;
64         struct syncres *s_restail;
65         ldap_pvt_thread_mutex_t s_mutex;
66 } syncops;
67
68 /* A received sync control */
69 typedef struct sync_control {
70         struct sync_cookie sr_state;
71         int sr_rhint;
72 } sync_control;
73
74 #if 0 /* moved back to slap.h */
75 #define o_sync  o_ctrlflag[slap_cids.sc_LDAPsync]
76 #endif
77 /* o_sync_mode uses data bits of o_sync */
78 #define o_sync_mode     o_ctrlflag[slap_cids.sc_LDAPsync]
79
80 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
81 #define SLAP_SYNC_REFRESH                               (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
82 #define SLAP_SYNC_PERSIST                               (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
83 #define SLAP_SYNC_REFRESH_AND_PERSIST   (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
84
85 #define PS_IS_REFRESHING        0x01
86 #define PS_IS_DETACHED          0x02
87
88 /* Record of which searches matched at premodify step */
89 typedef struct syncmatches {
90         struct syncmatches *sm_next;
91         syncops *sm_op;
92 } syncmatches;
93
94 /* Session log data */
95 typedef struct slog_entry {
96         struct slog_entry *se_next;
97         struct berval se_uuid;
98         struct berval se_csn;
99         ber_tag_t       se_tag;
100 } slog_entry;
101
102 typedef struct sessionlog {
103         struct berval   sl_mincsn;
104         int             sl_num;
105         int             sl_size;
106         slog_entry *sl_head;
107         slog_entry *sl_tail;
108         ldap_pvt_thread_mutex_t sl_mutex;
109 } sessionlog;
110
111 /* The main state for this overlay */
112 typedef struct syncprov_info_t {
113         syncops         *si_ops;
114         struct berval   si_ctxcsn;      /* ldapsync context */
115         int             si_chkops;      /* checkpointing info */
116         int             si_chktime;
117         int             si_numops;      /* number of ops since last checkpoint */
118         time_t  si_chklast;     /* time of last checkpoint */
119         Avlnode *si_mods;       /* entries being modified */
120         sessionlog      *si_logs;
121         ldap_pvt_thread_mutex_t si_csn_mutex;
122         ldap_pvt_thread_mutex_t si_ops_mutex;
123         ldap_pvt_thread_mutex_t si_mods_mutex;
124         char            si_ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
125 } syncprov_info_t;
126
127 typedef struct opcookie {
128         slap_overinst *son;
129         syncmatches *smatches;
130         struct berval sdn;      /* DN of entry, for deletes */
131         struct berval sndn;
132         struct berval suuid;    /* UUID of entry */
133         struct berval sctxcsn;
134         int sreference; /* Is the entry a reference? */
135 } opcookie;
136
137 typedef struct fbase_cookie {
138         struct berval *fdn;     /* DN of a modified entry, for scope testing */
139         syncops *fss;   /* persistent search we're testing against */
140         int fbase;      /* if TRUE we found the search base and it's still valid */
141         int fscope;     /* if TRUE then fdn is within the psearch scope */
142 } fbase_cookie;
143
144 static AttributeName csn_anlist[2];
145 static AttributeName uuid_anlist[2];
146
147 /* Build a LDAPsync intermediate state control */
148 static int
149 syncprov_state_ctrl(
150         Operation       *op,
151         SlapReply       *rs,
152         Entry           *e,
153         int             entry_sync_state,
154         LDAPControl     **ctrls,
155         int             num_ctrls,
156         int             send_cookie,
157         struct berval   *cookie )
158 {
159         Attribute* a;
160         int ret;
161         int res;
162         const char *text = NULL;
163
164         BerElementBuffer berbuf;
165         BerElement *ber = (BerElement *)&berbuf;
166
167         struct berval   entryuuid_bv = BER_BVNULL;
168
169         ber_init2( ber, 0, LBER_USE_DER );
170         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
171
172         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
173
174         for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
175                 AttributeDescription *desc = a->a_desc;
176                 if ( desc == slap_schema.si_ad_entryUUID ) {
177                         entryuuid_bv = a->a_nvals[0];
178                         break;
179                 }
180         }
181
182         if ( send_cookie && cookie ) {
183                 ber_printf( ber, "{eOON}",
184                         entry_sync_state, &entryuuid_bv, cookie );
185         } else {
186                 ber_printf( ber, "{eON}",
187                         entry_sync_state, &entryuuid_bv );
188         }
189
190         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
191         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
192         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
193
194         ber_free_buf( ber );
195
196         if ( ret < 0 ) {
197                 Debug( LDAP_DEBUG_TRACE,
198                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
199                         0, 0, 0 );
200                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
201                 return ret;
202         }
203
204         return LDAP_SUCCESS;
205 }
206
207 /* Build a LDAPsync final state control */
208 static int
209 syncprov_done_ctrl(
210         Operation       *op,
211         SlapReply       *rs,
212         LDAPControl     **ctrls,
213         int                     num_ctrls,
214         int                     send_cookie,
215         struct berval *cookie,
216         int                     refreshDeletes )
217 {
218         int ret;
219         BerElementBuffer berbuf;
220         BerElement *ber = (BerElement *)&berbuf;
221
222         ber_init2( ber, NULL, LBER_USE_DER );
223         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
224
225         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
226
227         ber_printf( ber, "{" );
228         if ( send_cookie && cookie ) {
229                 ber_printf( ber, "O", cookie );
230         }
231         if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
232                 ber_printf( ber, "b", refreshDeletes );
233         }
234         ber_printf( ber, "N}" );
235
236         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
237         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
238         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
239
240         ber_free_buf( ber );
241
242         if ( ret < 0 ) {
243                 Debug( LDAP_DEBUG_TRACE,
244                         "syncprov_done_ctrl: ber_flatten2 failed\n",
245                         0, 0, 0 );
246                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
247                 return ret;
248         }
249
250         return LDAP_SUCCESS;
251 }
252
253 #if 0
254 /* Generate state based on session log - not implemented yet */
255 static int
256 syncprov_state_ctrl_from_slog(
257         Operation       *op,
258         SlapReply       *rs,
259         struct slog_entry *slog_e,
260         int                     entry_sync_state,
261         LDAPControl     **ctrls,
262         int                     num_ctrls,
263         int                     send_cookie,
264         struct berval   *cookie)
265 {
266         Attribute* a;
267         int ret;
268         int res;
269         const char *text = NULL;
270
271         BerElementBuffer berbuf;
272         BerElement *ber = (BerElement *)&berbuf;
273
274         struct berval entryuuid_bv      = BER_BVNULL;
275
276         ber_init2( ber, NULL, LBER_USE_DER );
277         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
278
279         ctrls[num_ctrls] = ch_malloc ( sizeof ( LDAPControl ) );
280
281         entryuuid_bv = slog_e->sl_uuid;
282
283         if ( send_cookie && cookie ) {
284                 ber_printf( ber, "{eOON}",
285                         entry_sync_state, &entryuuid_bv, cookie );
286         } else {
287                 ber_printf( ber, "{eON}",
288                         entry_sync_state, &entryuuid_bv );
289         }
290
291         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
292         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
293         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
294
295         ber_free_buf( ber );
296
297         if ( ret < 0 ) {
298                 Debug( LDAP_DEBUG_TRACE,
299                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
300                         0, 0, 0 );
301                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
302                 return ret;
303         }
304
305         return LDAP_SUCCESS;
306 }
307 #endif
308
309 static int
310 syncprov_sendinfo(
311         Operation       *op,
312         SlapReply       *rs,
313         int                     type,
314         struct berval *cookie,
315         int                     refreshDone,
316         BerVarray       syncUUIDs,
317         int                     refreshDeletes )
318 {
319         BerElementBuffer berbuf;
320         BerElement *ber = (BerElement *)&berbuf;
321         struct berval rspdata;
322
323         int ret;
324
325         ber_init2( ber, NULL, LBER_USE_DER );
326         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
327
328         if ( type ) {
329                 switch ( type ) {
330                 case LDAP_TAG_SYNC_NEW_COOKIE:
331                         ber_printf( ber, "tO", type, cookie );
332                         break;
333                 case LDAP_TAG_SYNC_REFRESH_DELETE:
334                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
335                         ber_printf( ber, "t{", type );
336                         if ( cookie ) {
337                                 ber_printf( ber, "O", cookie );
338                         }
339                         if ( refreshDone == 0 ) {
340                                 ber_printf( ber, "b", refreshDone );
341                         }
342                         ber_printf( ber, "N}" );
343                         break;
344                 case LDAP_TAG_SYNC_ID_SET:
345                         ber_printf( ber, "t{", type );
346                         if ( cookie ) {
347                                 ber_printf( ber, "O", cookie );
348                         }
349                         if ( refreshDeletes == 1 ) {
350                                 ber_printf( ber, "b", refreshDeletes );
351                         }
352                         ber_printf( ber, "[W]", syncUUIDs );
353                         ber_printf( ber, "N}" );
354                         break;
355                 default:
356                         Debug( LDAP_DEBUG_TRACE,
357                                 "syncprov_sendinfo: invalid syncinfo type (%d)\n",
358                                 type, 0, 0 );
359                         return LDAP_OTHER;
360                 }
361         }
362
363         ret = ber_flatten2( ber, &rspdata, 0 );
364
365         if ( ret < 0 ) {
366                 Debug( LDAP_DEBUG_TRACE,
367                         "syncprov_sendinfo: ber_flatten2 failed\n",
368                         0, 0, 0 );
369                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
370                 return ret;
371         }
372
373         rs->sr_rspoid = LDAP_SYNC_INFO;
374         rs->sr_rspdata = &rspdata;
375         send_ldap_intermediate( op, rs );
376         rs->sr_rspdata = NULL;
377         ber_free_buf( ber );
378
379         return LDAP_SUCCESS;
380 }
381
382 /* Find a modtarget in an AVL tree */
383 static int
384 sp_avl_cmp( const void *c1, const void *c2 )
385 {
386         const modtarget *m1, *m2;
387         int rc;
388
389         m1 = c1; m2 = c2;
390         rc = m1->mt_op->o_req_ndn.bv_len - m2->mt_op->o_req_ndn.bv_len;
391
392         if ( rc ) return rc;
393         return ber_bvcmp( &m1->mt_op->o_req_ndn, &m2->mt_op->o_req_ndn );
394 }
395
396 /* syncprov_findbase:
397  *   finds the true DN of the base of a search (with alias dereferencing) and
398  * checks to make sure the base entry doesn't get replaced with a different
399  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
400  * change is detected, any persistent search on this base must be terminated /
401  * reloaded.
402  *   On the first call, we just save the DN and entryID. On subsequent calls
403  * we compare the DN and entryID with the saved values.
404  */
405 static int
406 findbase_cb( Operation *op, SlapReply *rs )
407 {
408         slap_callback *sc = op->o_callback;
409
410         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
411                 fbase_cookie *fc = sc->sc_private;
412
413                 /* If no entryID, we're looking for the first time.
414                  * Just store whatever we got.
415                  */
416                 if ( fc->fss->s_eid == NOID ) {
417                         fc->fbase = 1;
418                         fc->fss->s_eid = rs->sr_entry->e_id;
419                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
420
421                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
422                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
423
424                 /* OK, the DN is the same and the entryID is the same. Now
425                  * see if the fdn resides in the scope.
426                  */
427                         fc->fbase = 1;
428                         switch ( fc->fss->s_op->ors_scope ) {
429                         case LDAP_SCOPE_BASE:
430                                 fc->fscope = dn_match( fc->fdn, &rs->sr_entry->e_nname );
431                                 break;
432                         case LDAP_SCOPE_ONELEVEL: {
433                                 struct berval pdn;
434                                 dnParent( fc->fdn, &pdn );
435                                 fc->fscope = dn_match( &pdn, &rs->sr_entry->e_nname );
436                                 break; }
437                         case LDAP_SCOPE_SUBTREE:
438                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname );
439                                 break;
440 #ifdef LDAP_SCOPE_SUBORDINATE
441                         case LDAP_SCOPE_SUBORDINATE:
442                                 fc->fscope = dnIsSuffix( fc->fdn, &rs->sr_entry->e_nname ) &&
443                                         !dn_match( fc->fdn, &rs->sr_entry->e_nname );
444                                 break;
445 #endif
446                         }
447                 }
448         }
449         if ( rs->sr_err != LDAP_SUCCESS ) {
450                 Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err,0,0 );
451         }
452         return LDAP_SUCCESS;
453 }
454
455 static int
456 syncprov_findbase( Operation *op, fbase_cookie *fc )
457 {
458         opcookie *opc = op->o_callback->sc_private;
459         slap_overinst *on = opc->son;
460         syncprov_info_t         *si = on->on_bi.bi_private;
461
462         slap_callback cb = {0};
463         Operation fop;
464         SlapReply frs = { REP_RESULT };
465         int rc;
466
467         fop = *op;
468
469         cb.sc_response = findbase_cb;
470         cb.sc_private = fc;
471
472         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync mode */
473         fop.o_callback = &cb;
474         fop.o_tag = LDAP_REQ_SEARCH;
475         fop.ors_scope = LDAP_SCOPE_BASE;
476         fop.ors_deref = fc->fss->s_op->ors_deref;
477         fop.ors_limit = NULL;
478         fop.ors_slimit = 1;
479         fop.ors_tlimit = SLAP_NO_LIMIT;
480         fop.ors_attrs = slap_anlist_no_attrs;
481         fop.ors_attrsonly = 1;
482         fop.ors_filter = fc->fss->s_op->ors_filter;
483         fop.ors_filterstr = fc->fss->s_op->ors_filterstr;
484
485         fop.o_req_ndn = fc->fss->s_op->o_req_ndn;
486
487         fop.o_bd->bd_info = on->on_info->oi_orig;
488         rc = fop.o_bd->be_search( &fop, &frs );
489         fop.o_bd->bd_info = (BackendInfo *)on;
490
491         if ( fc->fbase ) return LDAP_SUCCESS;
492
493         /* If entryID has changed, then the base of this search has
494          * changed. Invalidate the psearch.
495          */
496         return LDAP_NO_SUCH_OBJECT;
497 }
498
499 /* syncprov_findcsn:
500  *   This function has three different purposes, but they all use a search
501  * that filters on entryCSN so they're combined here.
502  * 1: at startup time, after a contextCSN has been read from the database,
503  * we search for all entries with CSN >= contextCSN in case the contextCSN
504  * was not checkpointed at the previous shutdown.
505  *
506  * 2: when the current contextCSN is known and we have a sync cookie, we search
507  * for one entry with CSN <= the cookie CSN. (Used to search for =.) If an
508  * entry is found, the cookie CSN is valid, otherwise it is stale.
509  *
510  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
511  * CSN, and generate Present records for them. We always collect this result
512  * in SyncID sets, even if there's only one match.
513  */
514 #define FIND_MAXCSN     1
515 #define FIND_CSN        2
516 #define FIND_PRESENT    3
517
518 static int
519 findmax_cb( Operation *op, SlapReply *rs )
520 {
521         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
522                 struct berval *maxcsn = op->o_callback->sc_private;
523                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
524                         slap_schema.si_ad_entryCSN );
525
526                 if ( a && ber_bvcmp( &a->a_vals[0], maxcsn ) > 0 ) {
527                         maxcsn->bv_len = a->a_vals[0].bv_len;
528                         strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
529                 }
530         }
531         return LDAP_SUCCESS;
532 }
533
534 static int
535 findcsn_cb( Operation *op, SlapReply *rs )
536 {
537         slap_callback *sc = op->o_callback;
538
539         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
540                 sc->sc_private = (void *)1;
541         }
542         return LDAP_SUCCESS;
543 }
544
545 /* Build a list of entryUUIDs for sending in a SyncID set */
546
547 #define UUID_LEN        16
548
549 typedef struct fpres_cookie {
550         int num;
551         BerVarray uuids;
552         char *last;
553 } fpres_cookie;
554
555 static int
556 findpres_cb( Operation *op, SlapReply *rs )
557 {
558         slap_callback *sc = op->o_callback;
559         fpres_cookie *pc = sc->sc_private;
560         Attribute *a;
561         int ret = SLAP_CB_CONTINUE;
562
563         switch ( rs->sr_type ) {
564         case REP_SEARCH:
565                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
566                 if ( a ) {
567                         pc->uuids[pc->num].bv_val = pc->last;
568                         AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
569                                 pc->uuids[pc->num].bv_len );
570                         pc->num++;
571                         pc->last = pc->uuids[pc->num].bv_val;
572                         pc->uuids[pc->num].bv_val = NULL;
573                 }
574                 ret = LDAP_SUCCESS;
575                 if ( pc->num != SLAP_SYNCUUID_SET_SIZE )
576                         break;
577                 /* FALLTHRU */
578         case REP_RESULT:
579                 ret = rs->sr_err;
580                 if ( pc->num ) {
581                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
582                                 0, pc->uuids, 0 );
583                         pc->uuids[pc->num].bv_val = pc->last;
584                         pc->num = 0;
585                         pc->last = pc->uuids[0].bv_val;
586                 }
587                 break;
588         default:
589                 break;
590         }
591         return ret;
592 }
593
594 static int
595 syncprov_findcsn( Operation *op, int mode )
596 {
597         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
598         syncprov_info_t         *si = on->on_bi.bi_private;
599
600         slap_callback cb = {0};
601         Operation fop;
602         SlapReply frs = { REP_RESULT };
603         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
604         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
605         struct berval fbuf, maxcsn;
606         Filter cf, af;
607         AttributeAssertion eq;
608         int i, rc = LDAP_SUCCESS;
609         fpres_cookie pcookie;
610         sync_control *srs;
611
612         if ( mode != FIND_MAXCSN ) {
613                 srs = op->o_controls[slap_cids.sc_LDAPsync];
614
615                 if ( srs->sr_state.ctxcsn->bv_len >= LDAP_LUTIL_CSNSTR_BUFSIZE ) {
616                         return LDAP_OTHER;
617                 }
618         }
619
620         fop = *op;
621         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
622
623         fbuf.bv_val = buf;
624         cf.f_ava = &eq;
625         cf.f_av_desc = slap_schema.si_ad_entryCSN;
626         cf.f_next = NULL;
627
628         fop.o_callback = &cb;
629         fop.ors_limit = NULL;
630         fop.ors_tlimit = SLAP_NO_LIMIT;
631         fop.ors_filter = &cf;
632         fop.ors_filterstr = fbuf;
633
634         switch( mode ) {
635         case FIND_MAXCSN:
636                 cf.f_choice = LDAP_FILTER_GE;
637                 cf.f_av_value = si->si_ctxcsn;
638                 fbuf.bv_len = sprintf( buf, "(entryCSN>=%s)",
639                         cf.f_av_value.bv_val );
640                 fop.ors_attrsonly = 0;
641                 fop.ors_attrs = csn_anlist;
642                 fop.ors_slimit = SLAP_NO_LIMIT;
643                 cb.sc_private = &maxcsn;
644                 cb.sc_response = findmax_cb;
645                 strcpy( cbuf, si->si_ctxcsn.bv_val );
646                 maxcsn.bv_val = cbuf;
647                 maxcsn.bv_len = si->si_ctxcsn.bv_len;
648                 break;
649         case FIND_CSN:
650                 cf.f_choice = LDAP_FILTER_LE;
651                 cf.f_av_value = *srs->sr_state.ctxcsn;
652                 fbuf.bv_len = sprintf( buf, "(entryCSN<=%s)",
653                         cf.f_av_value.bv_val );
654                 fop.ors_attrsonly = 1;
655                 fop.ors_attrs = slap_anlist_no_attrs;
656                 fop.ors_slimit = 1;
657                 cb.sc_private = NULL;
658                 cb.sc_response = findcsn_cb;
659                 break;
660         case FIND_PRESENT:
661                 af.f_choice = LDAP_FILTER_AND;
662                 af.f_next = NULL;
663                 af.f_and = &cf;
664                 cf.f_choice = LDAP_FILTER_LE;
665                 cf.f_av_value = *srs->sr_state.ctxcsn;
666                 cf.f_next = op->ors_filter;
667                 fop.ors_filter = &af;
668                 filter2bv_x( &fop, fop.ors_filter, &fop.ors_filterstr );
669                 fop.ors_attrsonly = 0;
670                 fop.ors_attrs = uuid_anlist;
671                 fop.ors_slimit = SLAP_NO_LIMIT;
672                 /* We want pure entries, not referrals */
673                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
674                 cb.sc_private = &pcookie;
675                 cb.sc_response = findpres_cb;
676                 pcookie.num = 0;
677
678                 /* preallocate storage for a full set */
679                 pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
680                         sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
681                         op->o_tmpmemctx );
682                 pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
683                 pcookie.uuids[0].bv_val = pcookie.last;
684                 pcookie.uuids[0].bv_len = UUID_LEN;
685                 for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
686                         pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
687                         pcookie.uuids[i].bv_len = UUID_LEN;
688                 }
689                 break;
690         }
691
692         fop.o_bd->bd_info = on->on_info->oi_orig;
693         fop.o_bd->be_search( &fop, &frs );
694         fop.o_bd->bd_info = (BackendInfo *)on;
695
696         switch( mode ) {
697         case FIND_MAXCSN:
698                 strcpy( si->si_ctxcsnbuf, maxcsn.bv_val );
699                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
700                 break;
701         case FIND_CSN:
702                 /* If matching CSN was not found, invalidate the context. */
703                 if ( !cb.sc_private ) rc = LDAP_NO_SUCH_OBJECT;
704                 break;
705         case FIND_PRESENT:
706                 op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
707                 op->o_tmpfree( fop.ors_filterstr.bv_val, op->o_tmpmemctx );
708                 break;
709         }
710
711         return rc;
712 }
713
714 /* Queue a persistent search response if still in Refresh stage */
715 static int
716 syncprov_qresp( opcookie *opc, syncops *so, int mode )
717 {
718         syncres *sr;
719
720         sr = ch_malloc(sizeof(syncres) + opc->suuid.bv_len + 1 +
721                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1 + opc->sctxcsn.bv_len + 1 );
722         sr->s_next = NULL;
723         sr->s_dn.bv_val = (char *)(sr + 1);
724         sr->s_mode = mode;
725         sr->s_isreference = opc->sreference;
726         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val, opc->sdn.bv_val );
727         *(sr->s_ndn.bv_val++) = '\0';
728         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val, opc->sndn.bv_val );
729         *(sr->s_uuid.bv_val++) = '\0';
730         sr->s_csn.bv_val = lutil_strcopy( sr->s_uuid.bv_val, opc->suuid.bv_val );
731
732         if ( !so->s_res ) {
733                 so->s_res = sr;
734         } else {
735                 so->s_restail->s_next = sr;
736         }
737         so->s_restail = sr;
738         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
739         return LDAP_SUCCESS;
740 }
741
742 /* Send a persistent search response */
743 static int
744 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, Entry *e, int mode, int queue )
745 {
746         slap_overinst *on = opc->son;
747         syncprov_info_t *si = on->on_bi.bi_private;
748
749         SlapReply rs = { REP_SEARCH };
750         LDAPControl *ctrls[2];
751         struct berval cookie;
752         Entry e_uuid = {0};
753         Attribute a_uuid = {0};
754         Operation sop = *so->s_op;
755         Opheader ohdr;
756
757         ohdr = *sop.o_hdr;
758         sop.o_hdr = &ohdr;
759         sop.o_tmpmemctx = op->o_tmpmemctx;
760         sop.o_bd = op->o_bd;
761         sop.o_controls = op->o_controls;
762
763         if ( queue && (so->s_flags & PS_IS_REFRESHING) ) {
764                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
765                 if ( so->s_flags & PS_IS_REFRESHING )
766                         return syncprov_qresp( opc, so, mode );
767                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
768         }
769
770         ctrls[1] = NULL;
771         slap_compose_sync_cookie( op, &cookie, &opc->sctxcsn, so->s_rid );
772
773         e_uuid.e_attrs = &a_uuid;
774         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
775         a_uuid.a_nvals = &opc->suuid;
776         rs.sr_err = syncprov_state_ctrl( &sop, &rs, &e_uuid,
777                 mode, ctrls, 0, 1, &cookie );
778
779         rs.sr_entry = e;
780         rs.sr_ctrls = ctrls;
781         switch( mode ) {
782         case LDAP_SYNC_ADD:
783                 if ( opc->sreference ) {
784                         rs.sr_ref = get_entry_referrals( &sop, e );
785                         send_search_reference( &sop, &rs );
786                         ber_bvarray_free( rs.sr_ref );
787                         break;
788                 }
789                 /* fallthru */
790         case LDAP_SYNC_MODIFY:
791                 rs.sr_attrs = sop.ors_attrs;
792                 send_search_entry( &sop, &rs );
793                 break;
794         case LDAP_SYNC_DELETE:
795                 e_uuid.e_attrs = NULL;
796                 e_uuid.e_name = opc->sdn;
797                 e_uuid.e_nname = opc->sndn;
798                 rs.sr_entry = &e_uuid;
799                 if ( opc->sreference ) {
800                         struct berval bv = BER_BVNULL;
801                         rs.sr_ref = &bv;
802                         send_search_reference( &sop, &rs );
803                 } else {
804                         send_search_entry( &sop, &rs );
805                 }
806                 break;
807         default:
808                 assert(0);
809         }
810         op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
811         rs.sr_ctrls = NULL;
812         return rs.sr_err;
813 }
814
815 static void
816 syncprov_free_syncop( syncops *so )
817 {
818         syncres *sr, *srnext;
819         GroupAssertion *ga, *gnext;
820
821         ldap_pvt_thread_mutex_lock( &so->s_mutex );
822         so->s_inuse--;
823         if ( so->s_inuse > 0 ) {
824                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
825                 return;
826         }
827         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
828         if ( so->s_flags & PS_IS_DETACHED ) {
829                 filter_free( so->s_op->ors_filter );
830                 for ( ga = so->s_op->o_groups; ga; ga=gnext ) {
831                         gnext = ga->ga_next;
832                         ch_free( ga );
833                 }
834                 ch_free( so->s_op );
835         }
836         ch_free( so->s_base.bv_val );
837         for ( sr=so->s_res; sr; sr=srnext ) {
838                 srnext = sr->s_next;
839                 ch_free( sr );
840         }
841         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
842         ch_free( so );
843 }
844
845 static int
846 syncprov_drop_psearch( syncops *so, int lock )
847 {
848         if ( so->s_flags & PS_IS_DETACHED ) {
849                 if ( lock )
850                         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
851                 so->s_op->o_conn->c_n_ops_executing--;
852                 so->s_op->o_conn->c_n_ops_completed++;
853                 LDAP_STAILQ_REMOVE( &so->s_op->o_conn->c_ops, so->s_op, slap_op,
854                         o_next );
855                 if ( lock )
856                         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
857         }
858         syncprov_free_syncop( so );
859 }
860
861 static int
862 syncprov_op_abandon( Operation *op, SlapReply *rs )
863 {
864         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
865         syncprov_info_t         *si = on->on_bi.bi_private;
866         syncops *so, *soprev;
867
868         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
869         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
870                 soprev=so, so=so->s_next ) {
871                 if ( so->s_op->o_connid == op->o_connid &&
872                         so->s_op->o_msgid == op->orn_msgid ) {
873                                 so->s_op->o_abandon = 1;
874                                 soprev->s_next = so->s_next;
875                                 break;
876                 }
877         }
878         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
879         if ( so ) {
880                 /* Is this really a Cancel exop? */
881                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
882                         rs->sr_err = LDAP_CANCELLED;
883                         send_ldap_result( so->s_op, rs );
884                 }
885                 syncprov_drop_psearch( so, 0 );
886         }
887         return SLAP_CB_CONTINUE;
888 }
889
890 /* Find which persistent searches are affected by this operation */
891 static void
892 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
893 {
894         slap_overinst *on = opc->son;
895         syncprov_info_t         *si = on->on_bi.bi_private;
896
897         fbase_cookie fc;
898         syncops *ss, *sprev, *snext;
899         Entry *e;
900         Attribute *a;
901         int rc;
902         struct berval newdn;
903         int freefdn = 0;
904
905         fc.fdn = &op->o_req_ndn;
906         /* compute new DN */
907         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
908                 struct berval pdn;
909                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
910                 else dnParent( fc.fdn, &pdn );
911                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
912                 fc.fdn = &newdn;
913                 freefdn = 1;
914         }
915         if ( op->o_tag != LDAP_REQ_ADD ) {
916                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
917                 rc = be_entry_get_rw( op, fc.fdn, NULL, NULL, 0, &e );
918                 op->o_bd->bd_info = (BackendInfo *)on;
919                 if ( rc ) return;
920         } else {
921                 e = op->ora_e;
922         }
923
924         /* Never replicate these */
925         if ( is_entry_syncConsumerSubentry( e )) {
926                 goto done;
927         }
928         if ( saveit ) {
929                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
930                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
931                 opc->sreference = is_entry_referral( e );
932         }
933         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
934                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
935                 if ( a )
936                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
937         }
938
939         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
940         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
941                 sprev = ss, ss=snext)
942         {
943                 syncmatches *sm;
944                 int found = 0;
945
946                 snext = ss->s_next;
947                 /* validate base */
948                 fc.fss = ss;
949                 fc.fbase = 0;
950                 fc.fscope = 0;
951
952                 /* If the base of the search is missing, signal a refresh */
953                 rc = syncprov_findbase( op, &fc );
954                 if ( rc != LDAP_SUCCESS ) {
955                         SlapReply rs = {REP_RESULT};
956                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
957                                 "search base has changed" );
958                         sprev->s_next = snext;
959                         syncprov_drop_psearch( ss, 1 );
960                         continue;
961                 }
962
963                 /* If we're sending results now, look for this op in old matches */
964                 if ( !saveit ) {
965                         syncmatches *old;
966                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
967                                 old=sm, sm=sm->sm_next ) {
968                                 if ( sm->sm_op == ss ) {
969                                         found = 1;
970                                         old->sm_next = sm->sm_next;
971                                         op->o_tmpfree( sm, op->o_tmpmemctx );
972                                         break;
973                                 }
974                         }
975                 }
976
977                 /* check if current o_req_dn is in scope and matches filter */
978                 if ( fc.fscope && test_filter( op, e, ss->s_op->ors_filter ) ==
979                         LDAP_COMPARE_TRUE ) {
980                         if ( saveit ) {
981                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
982                                 sm->sm_next = opc->smatches;
983                                 sm->sm_op = ss;
984                                 ss->s_inuse++;
985                                 opc->smatches = sm;
986                         } else {
987                                 /* if found send UPDATE else send ADD */
988                                 syncprov_sendresp( op, opc, ss, e,
989                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD, 1 );
990                         }
991                 } else if ( !saveit && found ) {
992                         /* send DELETE */
993                         syncprov_sendresp( op, opc, ss, NULL, LDAP_SYNC_DELETE, 1 );
994                 }
995         }
996         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
997 done:
998         if ( op->o_tag != LDAP_REQ_ADD ) {
999                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1000                 be_entry_release_rw( op, e, 0 );
1001                 op->o_bd->bd_info = (BackendInfo *)on;
1002         }
1003         if ( freefdn ) {
1004                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
1005         }
1006 }
1007
1008 static int
1009 syncprov_op_cleanup( Operation *op, SlapReply *rs )
1010 {
1011         slap_callback *cb = op->o_callback;
1012         opcookie *opc = cb->sc_private;
1013         slap_overinst *on = opc->son;
1014         syncprov_info_t         *si = on->on_bi.bi_private;
1015         syncmatches *sm, *snext;
1016         modtarget *mt, mtdummy;
1017
1018         for (sm = opc->smatches; sm; sm=snext) {
1019                 snext = sm->sm_next;
1020                 syncprov_free_syncop( sm->sm_op );
1021                 op->o_tmpfree( sm, op->o_tmpmemctx );
1022         }
1023
1024         /* Remove op from lock table */
1025         mtdummy.mt_op = op;
1026         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1027         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1028         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1029         if ( mt ) {
1030                 modinst *mi = mt->mt_mods;
1031
1032                 /* If there are more, promote the next one */
1033                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1034                 if ( mi->mi_next ) {
1035                         mt->mt_mods = mi->mi_next;
1036                         mt->mt_op = mt->mt_mods->mi_op;
1037                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1038                 } else {
1039                         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1040                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
1041                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1042                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1043                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1044                         ch_free( mt );
1045                 }
1046         }
1047         if ( !BER_BVISNULL( &opc->suuid ))
1048                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1049         if ( !BER_BVISNULL( &opc->sndn ))
1050                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1051         if ( !BER_BVISNULL( &opc->sdn ))
1052                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1053         op->o_callback = cb->sc_next;
1054         op->o_tmpfree(cb, op->o_tmpmemctx);
1055 }
1056
1057 static void
1058 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1059 {
1060         syncprov_info_t         *si = on->on_bi.bi_private;
1061         Modifications mod;
1062         Operation opm;
1063         struct berval bv[2];
1064         BackendInfo *orig;
1065         slap_callback cb = {0};
1066
1067         mod.sml_values = bv;
1068         bv[1].bv_val = NULL;
1069         bv[0] = si->si_ctxcsn;
1070         mod.sml_nvalues = NULL;
1071         mod.sml_desc = slap_schema.si_ad_contextCSN;
1072         mod.sml_op = LDAP_MOD_REPLACE;
1073         mod.sml_next = NULL;
1074
1075         cb.sc_response = slap_null_cb;
1076         opm = *op;
1077         opm.o_tag = LDAP_REQ_MODIFY;
1078         opm.o_callback = &cb;
1079         opm.orm_modlist = &mod;
1080         opm.o_req_dn = op->o_bd->be_suffix[0];
1081         opm.o_req_ndn = op->o_bd->be_nsuffix[0];
1082         orig = opm.o_bd->bd_info;
1083         opm.o_bd->bd_info = on->on_info->oi_orig;
1084         opm.o_bd->be_modify( &opm, rs );
1085 }
1086
1087 static void
1088 syncprov_add_slog( Operation *op, struct berval *csn )
1089 {
1090         opcookie *opc = op->o_callback->sc_private;
1091         slap_overinst *on = opc->son;
1092         syncprov_info_t         *si = on->on_bi.bi_private;
1093         sessionlog *sl;
1094         slog_entry *se;
1095
1096         sl = si->si_logs;
1097         {
1098                 /* Allocate a record. UUIDs are not NUL-terminated. */
1099                 se = ch_malloc( sizeof( slog_entry ) + opc->suuid.bv_len + 
1100                         csn->bv_len + 1 );
1101                 se->se_next = NULL;
1102                 se->se_tag = op->o_tag;
1103
1104                 se->se_uuid.bv_val = (char *)(se+1);
1105                 se->se_csn.bv_val = se->se_uuid.bv_val + opc->suuid.bv_len + 1;
1106                 AC_MEMCPY( se->se_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1107                 se->se_uuid.bv_len = opc->suuid.bv_len;
1108
1109                 AC_MEMCPY( se->se_csn.bv_val, csn->bv_val, csn->bv_len );
1110                 se->se_csn.bv_val[csn->bv_len] = '\0';
1111                 se->se_csn.bv_len = csn->bv_len;
1112
1113                 ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
1114                 if ( sl->sl_head ) {
1115                         sl->sl_tail->se_next = se;
1116                 } else {
1117                         sl->sl_head = se;
1118                 }
1119                 sl->sl_tail = se;
1120                 sl->sl_num++;
1121                 while ( sl->sl_num > sl->sl_size ) {
1122                         se = sl->sl_head;
1123                         sl->sl_head = se->se_next;
1124                         strcpy( sl->sl_mincsn.bv_val, se->se_csn.bv_val );
1125                         sl->sl_mincsn.bv_len = se->se_csn.bv_len;
1126                         ch_free( se );
1127                         sl->sl_num--;
1128                         if ( !sl->sl_head ) {
1129                                 sl->sl_tail = NULL;
1130                         }
1131                 }
1132                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1133         }
1134 }
1135
1136 /* Just set a flag if we found the matching entry */
1137 static int
1138 playlog_cb( Operation *op, SlapReply *rs )
1139 {
1140         if ( rs->sr_type == REP_SEARCH ) {
1141                 op->o_callback->sc_private = (void *)1;
1142         }
1143         return rs->sr_err;
1144 }
1145
1146 /* enter with sl->sl_mutex locked, release before returning */
1147 static void
1148 syncprov_playlog( Operation *op, SlapReply *rs, sessionlog *sl,
1149         struct berval *oldcsn, struct berval *ctxcsn )
1150 {
1151         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1152         syncprov_info_t         *si = on->on_bi.bi_private;
1153         slog_entry *se;
1154         int i, j, ndel, num, nmods, mmods;
1155         BerVarray uuids;
1156
1157         if ( !sl->sl_num ) {
1158                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1159                 return;
1160         }
1161
1162         num = sl->sl_num;
1163         i = 0;
1164         nmods = 0;
1165
1166         uuids = op->o_tmpalloc( (num+1) * sizeof( struct berval ) +
1167                 num * UUID_LEN, op->o_tmpmemctx );
1168
1169         uuids[0].bv_val = (char *)(uuids + num + 1);
1170
1171         /* Make a copy of the relevant UUIDs. Put the Deletes up front
1172          * and everything else at the end. Do this first so we can
1173          * unlock the list mutex.
1174          */
1175         for ( se=sl->sl_head; se; se=se->se_next ) {
1176                 if ( ber_bvcmp( &se->se_csn, oldcsn ) < 0 ) continue;
1177                 if ( ber_bvcmp( &se->se_csn, ctxcsn ) > 0 ) break;
1178                 if ( se->se_tag == LDAP_REQ_DELETE ) {
1179                         j = i;
1180                         i++;
1181                 } else {
1182                         nmods++;
1183                         j = num - nmods;
1184                 }
1185                 uuids[j].bv_val = uuids[0].bv_val + (j * UUID_LEN);
1186                 AC_MEMCPY(uuids[j].bv_val, se->se_uuid.bv_val, UUID_LEN);
1187                 uuids[j].bv_len = UUID_LEN;
1188         }
1189         ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1190
1191         ndel = i;
1192
1193         /* Zero out unused slots */
1194         for ( i=ndel; i < num - nmods; i++ )
1195                 uuids[i].bv_len = 0;
1196
1197         /* Mods must be validated to see if they belong in this delete set.
1198          */
1199
1200         mmods = nmods;
1201         /* Strip any duplicates */
1202         for ( i=0; i<nmods; i++ ) {
1203                 for ( j=0; j<ndel; j++ ) {
1204                         if ( bvmatch( &uuids[j], &uuids[num - 1 - i] )) {
1205                                 uuids[num - 1 - i].bv_len = 0;
1206                                 mmods --;
1207                                 break;
1208                         }
1209                 }
1210                 if ( uuids[num - 1 - i].bv_len == 0 ) continue;
1211                 for ( j=0; j<i; j++ ) {
1212                         if ( bvmatch( &uuids[num - 1 - j], &uuids[num - 1 - i] )) {
1213                                 uuids[num - 1 - i].bv_len = 0;
1214                                 mmods --;
1215                                 break;
1216                         }
1217                 }
1218         }
1219
1220         if ( mmods ) {
1221                 Operation fop;
1222                 SlapReply frs = { REP_RESULT };
1223                 int rc;
1224                 Filter mf, af;
1225                 AttributeAssertion eq;
1226                 slap_callback cb = {0};
1227
1228                 fop = *op;
1229
1230                 fop.o_sync_mode = 0;
1231                 fop.o_callback = &cb;
1232                 fop.ors_limit = NULL;
1233                 fop.ors_tlimit = SLAP_NO_LIMIT;
1234                 fop.ors_attrs = slap_anlist_all_attributes;
1235                 fop.ors_attrsonly = 0;
1236                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
1237
1238                 af.f_choice = LDAP_FILTER_AND;
1239                 af.f_next = NULL;
1240                 af.f_and = &mf;
1241                 mf.f_choice = LDAP_FILTER_EQUALITY;
1242                 mf.f_ava = &eq;
1243                 mf.f_av_desc = slap_schema.si_ad_entryUUID;
1244                 mf.f_next = fop.ors_filter;
1245
1246                 fop.ors_filter = &af;
1247
1248                 cb.sc_response = playlog_cb;
1249                 fop.o_bd->bd_info = on->on_info->oi_orig;
1250
1251                 for ( i=ndel; i<num; i++ ) {
1252                         if ( uuids[i].bv_len == 0 ) continue;
1253
1254                         mf.f_av_value = uuids[i];
1255                         cb.sc_private = NULL;
1256                         fop.ors_slimit = 1;
1257                         rc = fop.o_bd->be_search( &fop, &frs );
1258
1259                         /* If entry was not found, add to delete list */
1260                         if ( !cb.sc_private ) {
1261                                 uuids[ndel++] = uuids[i];
1262                         }
1263                 }
1264                 fop.o_bd->bd_info = (BackendInfo *)on;
1265         }
1266         if ( ndel ) {
1267                 uuids[ndel].bv_val = NULL;
1268                 syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL, 0, uuids, 1 );
1269         }
1270 }
1271
1272 static int
1273 syncprov_op_response( Operation *op, SlapReply *rs )
1274 {
1275         opcookie *opc = op->o_callback->sc_private;
1276         slap_overinst *on = opc->son;
1277         syncprov_info_t         *si = on->on_bi.bi_private;
1278         syncmatches *sm;
1279
1280         if ( rs->sr_err == LDAP_SUCCESS )
1281         {
1282                 struct berval maxcsn = BER_BVNULL, curcsn = BER_BVNULL;
1283                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1284
1285                 /* Update our context CSN */
1286                 cbuf[0] = '\0';
1287                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1288                 slap_get_commit_csn( op, &maxcsn, &curcsn );
1289                 if ( !BER_BVISNULL( &maxcsn ) ) {
1290                         strcpy( cbuf, maxcsn.bv_val );
1291                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn ) > 0 ) {
1292                                 strcpy( si->si_ctxcsnbuf, cbuf );
1293                                 si->si_ctxcsn.bv_len = maxcsn.bv_len;
1294                         }
1295                 }
1296
1297                 si->si_numops++;
1298                 if ( si->si_chkops || si->si_chktime ) {
1299                         int do_check=0;
1300                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1301                                 do_check = 1;
1302                                 si->si_numops = 0;
1303                         }
1304                         if ( si->si_chktime &&
1305                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1306                                 do_check = 1;
1307                                 si->si_chklast = op->o_time;
1308                         }
1309                         if ( do_check ) {
1310                                 syncprov_checkpoint( op, rs, on );
1311                         }
1312                 }
1313                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1314
1315                 opc->sctxcsn.bv_len = maxcsn.bv_len;
1316                 opc->sctxcsn.bv_val = cbuf;
1317
1318                 /* Handle any persistent searches */
1319                 if ( si->si_ops ) {
1320                         switch(op->o_tag) {
1321                         case LDAP_REQ_ADD:
1322                         case LDAP_REQ_MODIFY:
1323                         case LDAP_REQ_MODRDN:
1324                         case LDAP_REQ_EXTENDED:
1325                                 syncprov_matchops( op, opc, 0 );
1326                                 break;
1327                         case LDAP_REQ_DELETE:
1328                                 /* for each match in opc->smatches:
1329                                  *   send DELETE msg
1330                                  */
1331                                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1332                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1333                                         if ( sm->sm_op->s_op->o_abandon )
1334                                                 continue;
1335                                         syncprov_sendresp( op, opc, sm->sm_op, NULL,
1336                                                 LDAP_SYNC_DELETE, 1 );
1337                                 }
1338                                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1339                                 break;
1340                         }
1341                 }
1342
1343                 /* Add any log records */
1344                 if ( si->si_logs && op->o_tag != LDAP_REQ_ADD ) {
1345                         syncprov_add_slog( op, &curcsn );
1346                 }
1347
1348         }
1349         return SLAP_CB_CONTINUE;
1350 }
1351
1352 /* We don't use a subentry to store the context CSN any more.
1353  * We expose the current context CSN as an operational attribute
1354  * of the suffix entry.
1355  */
1356 static int
1357 syncprov_op_compare( Operation *op, SlapReply *rs )
1358 {
1359         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1360         syncprov_info_t         *si = on->on_bi.bi_private;
1361         int rc = SLAP_CB_CONTINUE;
1362
1363         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1364                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1365         {
1366                 Entry e = {0};
1367                 Attribute a = {0};
1368                 struct berval bv[2];
1369
1370                 e.e_name = op->o_bd->be_suffix[0];
1371                 e.e_nname = op->o_bd->be_nsuffix[0];
1372
1373                 BER_BVZERO( &bv[1] );
1374                 bv[0] = si->si_ctxcsn;
1375
1376                 a.a_desc = slap_schema.si_ad_contextCSN;
1377                 a.a_vals = bv;
1378                 a.a_nvals = a.a_vals;
1379
1380                 ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1381
1382                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1383                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1384                 if ( ! rs->sr_err ) {
1385                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1386                         goto return_results;
1387                 }
1388
1389                 if ( get_assert( op ) &&
1390                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1391                 {
1392                         rs->sr_err = LDAP_ASSERTION_FAILED;
1393                         goto return_results;
1394                 }
1395
1396
1397                 rs->sr_err = LDAP_COMPARE_FALSE;
1398
1399                 if ( value_find_ex( op->oq_compare.rs_ava->aa_desc,
1400                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1401                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1402                                 a.a_nvals, &op->oq_compare.rs_ava->aa_value, op->o_tmpmemctx ) == 0 )
1403                 {
1404                         rs->sr_err = LDAP_COMPARE_TRUE;
1405                 }
1406
1407 return_results:;
1408
1409                 ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1410
1411                 send_ldap_result( op, rs );
1412
1413                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1414                         rs->sr_err = LDAP_SUCCESS;
1415                 }
1416                 rc = rs->sr_err;
1417         }
1418
1419         return rc;
1420 }
1421
1422 static int
1423 syncprov_op_mod( Operation *op, SlapReply *rs )
1424 {
1425         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1426         syncprov_info_t         *si = on->on_bi.bi_private;
1427
1428         slap_callback *cb = op->o_tmpcalloc(1, sizeof(slap_callback)+
1429                 sizeof(opcookie) +
1430                 (si->si_ops ? sizeof(modinst) : 0 ),
1431                 op->o_tmpmemctx);
1432         opcookie *opc = (opcookie *)(cb+1);
1433         opc->son = on;
1434         cb->sc_response = syncprov_op_response;
1435         cb->sc_cleanup = syncprov_op_cleanup;
1436         cb->sc_private = opc;
1437         cb->sc_next = op->o_callback;
1438         op->o_callback = cb;
1439
1440         /* If there are active persistent searches, lock this operation.
1441          * See seqmod.c for the locking logic on its own.
1442          */
1443         if ( si->si_ops ) {
1444                 modtarget *mt, mtdummy;
1445                 modinst *mi;
1446
1447                 mi = (modinst *)(opc+1);
1448                 mi->mi_op = op;
1449
1450                 /* See if we're already modifying this entry... */
1451                 mtdummy.mt_op = op;
1452                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1453                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1454                 if ( mt ) {
1455                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1456                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1457                         mt->mt_tail->mi_next = mi;
1458                         mt->mt_tail = mi;
1459                         /* wait for this op to get to head of list */
1460                         while ( mt->mt_mods != mi ) {
1461                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1462                                 ldap_pvt_thread_yield();
1463                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1464                         }
1465                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1466                 } else {
1467                         /* Record that we're modifying this entry now */
1468                         mt = ch_malloc( sizeof(modtarget) );
1469                         mt->mt_mods = mi;
1470                         mt->mt_tail = mi;
1471                         mt->mt_op = mi->mi_op;
1472                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1473                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1474                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1475                 }
1476         }
1477
1478         if (( si->si_ops || si->si_logs ) && op->o_tag != LDAP_REQ_ADD )
1479                 syncprov_matchops( op, opc, 1 );
1480                 
1481
1482         return SLAP_CB_CONTINUE;
1483 }
1484
1485 static int
1486 syncprov_op_extended( Operation *op, SlapReply *rs )
1487 {
1488         if ( exop_is_write( op ))
1489                 return syncprov_op_mod( op, rs );
1490
1491         return SLAP_CB_CONTINUE;
1492 }
1493
1494 typedef struct searchstate {
1495         slap_overinst *ss_on;
1496         syncops *ss_so;
1497         int ss_present;
1498 } searchstate;
1499
1500 static int
1501 syncprov_search_cleanup( Operation *op, SlapReply *rs )
1502 {
1503         if ( rs->sr_ctrls ) {
1504                 op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
1505                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
1506                 rs->sr_ctrls = NULL;
1507         }
1508         return 0;
1509 }
1510
1511 static void
1512 syncprov_detach_op( Operation *op, syncops *so )
1513 {
1514         Operation *op2;
1515         int i, alen = 0;
1516         size_t size;
1517         char *ptr;
1518         GroupAssertion *g1, *g2;
1519
1520         /* count the search attrs */
1521         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1522                 alen += op->ors_attrs[i].an_name.bv_len + 1;
1523         }
1524         /* Make a new copy of the operation */
1525         size = sizeof(Operation) + sizeof(Opheader) +
1526                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
1527                 op->o_req_dn.bv_len + 1 +
1528                 op->o_req_ndn.bv_len + 1 +
1529                 op->o_ndn.bv_len + 1 +
1530                 so->s_filterstr.bv_len + 1;
1531         op2 = (Operation *)ch_calloc( 1, size );
1532         op2->o_hdr = (Opheader *)(op2+1);
1533
1534         /* Copy the fields we care about explicitly, leave the rest alone */
1535         *op2->o_hdr = *op->o_hdr;
1536         op2->o_tag = op->o_tag;
1537         op2->o_time = op->o_time;
1538         op2->o_bd = op->o_bd;
1539         op2->o_request = op->o_request;
1540
1541         if ( i ) {
1542                 op2->ors_attrs = (AttributeName *)(op2->o_hdr + 1);
1543                 ptr = (char *)(op2->ors_attrs+i+1);
1544                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
1545                         op2->ors_attrs[i] = op->ors_attrs[i];
1546                         op2->ors_attrs[i].an_name.bv_val = ptr;
1547                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
1548                 }
1549                 BER_BVZERO( &op2->ors_attrs[i].an_name );
1550         } else {
1551                 ptr = (char *)(op2->o_hdr + 1);
1552         }
1553         op2->o_authz = op->o_authz;
1554         op2->o_ndn.bv_val = ptr;
1555         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
1556         op2->o_dn = op2->o_ndn;
1557         op2->o_req_dn.bv_len = op->o_req_dn.bv_len;
1558         op2->o_req_dn.bv_val = ptr;
1559         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
1560         op2->o_req_ndn.bv_len = op->o_req_ndn.bv_len;
1561         op2->o_req_ndn.bv_val = ptr;
1562         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
1563         op2->ors_filterstr.bv_val = ptr;
1564         strcpy( ptr, so->s_filterstr.bv_val );
1565         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
1566         op2->ors_filter = str2filter( ptr );
1567         so->s_op = op2;
1568
1569         /* Copy any cached group ACLs individually */
1570         op2->o_groups = NULL;
1571         for ( g1=op->o_groups; g1; g1=g1->ga_next ) {
1572                 g2 = ch_malloc( sizeof(GroupAssertion) + g1->ga_len );
1573                 *g2 = *g1;
1574                 strcpy( g2->ga_ndn, g1->ga_ndn );
1575                 g2->ga_next = op2->o_groups;
1576                 op2->o_groups = g2;
1577         }
1578
1579         /* Add op2 to conn so abandon will find us */
1580         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1581         op->o_conn->c_n_ops_executing++;
1582         op->o_conn->c_n_ops_completed--;
1583         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op2, o_next );
1584         so->s_flags |= PS_IS_DETACHED;
1585         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1586 }
1587
1588 static int
1589 syncprov_search_response( Operation *op, SlapReply *rs )
1590 {
1591         searchstate *ss = op->o_callback->sc_private;
1592         slap_overinst *on = ss->ss_on;
1593         syncprov_info_t         *si = on->on_bi.bi_private;
1594         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
1595
1596         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
1597                 int i;
1598                 /* If we got a referral without a referral object, there's
1599                  * something missing that we cannot replicate. Just ignore it.
1600                  * The consumer will abort because we didn't send the expected
1601                  * control.
1602                  */
1603                 if ( !rs->sr_entry ) {
1604                         assert( rs->sr_entry );
1605                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
1606                         return SLAP_CB_CONTINUE;
1607                 }
1608                 if ( srs->sr_state.ctxcsn ) {
1609                         Attribute *a = attr_find( rs->sr_entry->e_attrs,
1610                                 slap_schema.si_ad_entryCSN );
1611                         
1612                         /* Don't send the ctx entry twice */
1613                         if ( a && bvmatch( &a->a_nvals[0], srs->sr_state.ctxcsn ) )
1614                                 return LDAP_SUCCESS;
1615                 }
1616                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1617                         op->o_tmpmemctx );
1618                 rs->sr_ctrls[1] = NULL;
1619                 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
1620                         LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
1621         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
1622                 struct berval cookie;
1623
1624                 slap_compose_sync_cookie( op, &cookie,
1625                         &op->ors_filter->f_and->f_ava->aa_value,
1626                         srs->sr_state.rid );
1627
1628                 /* Is this a regular refresh? */
1629                 if ( !ss->ss_so ) {
1630                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
1631                                 op->o_tmpmemctx );
1632                         rs->sr_ctrls[1] = NULL;
1633                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
1634                                 0, 1, &cookie, ss->ss_present ?  LDAP_SYNC_REFRESH_PRESENTS :
1635                                         LDAP_SYNC_REFRESH_DELETES );
1636                 } else {
1637                         int locked = 0;
1638                 /* It's RefreshAndPersist, transition to Persist phase */
1639                         syncprov_sendinfo( op, rs, ( ss->ss_present && rs->sr_nentries ) ?
1640                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
1641                                 &cookie, 1, NULL, 0 );
1642                         /* Flush any queued persist messages */
1643                         if ( ss->ss_so->s_res ) {
1644                                 syncres *sr, *srnext;
1645                                 Entry *e;
1646                                 opcookie opc;
1647
1648                                 opc.son = on;
1649                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
1650                                 locked = 1;
1651                                 for (sr = ss->ss_so->s_res; sr; sr=srnext) {
1652                                         int rc = LDAP_SUCCESS;
1653                                         srnext = sr->s_next;
1654                                         opc.sdn = sr->s_dn;
1655                                         opc.sndn = sr->s_ndn;
1656                                         opc.suuid = sr->s_uuid;
1657                                         opc.sctxcsn = sr->s_csn;
1658                                         opc.sreference = sr->s_isreference;
1659                                         e = NULL;
1660
1661                                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
1662                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1663                                                 rc = be_entry_get_rw( op, &opc.sndn, NULL, NULL, 0, &e );
1664                                                 op->o_bd->bd_info = (BackendInfo *)on;
1665                                         }
1666                                         if ( rc == LDAP_SUCCESS )
1667                                                 syncprov_sendresp( op, &opc, ss->ss_so, e,
1668                                                         sr->s_mode, 0 );
1669
1670                                         if ( e ) {
1671                                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1672                                                 be_entry_release_rw( op, e, 0 );
1673                                                 op->o_bd->bd_info = (BackendInfo *)on;
1674                                         }
1675                                         ch_free( sr );
1676                                 }
1677                                 ss->ss_so->s_res = NULL;
1678                                 ss->ss_so->s_restail = NULL;
1679                         }
1680
1681                         /* Turn off the refreshing flag */
1682                         ss->ss_so->s_flags ^= PS_IS_REFRESHING;
1683                         if ( locked )
1684                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
1685
1686                         /* Detach this Op from frontend control */
1687                         syncprov_detach_op( op, ss->ss_so );
1688
1689                         return LDAP_SUCCESS;
1690                 }
1691         }
1692
1693         return SLAP_CB_CONTINUE;
1694 }
1695
1696 static int
1697 syncprov_op_search( Operation *op, SlapReply *rs )
1698 {
1699         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1700         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1701         slap_callback   *cb;
1702         int gotstate = 0, nochange = 0, do_present = 1;
1703         Filter *fand, *fava;
1704         syncops *sop = NULL;
1705         searchstate *ss;
1706         sync_control *srs;
1707         struct berval ctxcsn;
1708         char csnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1709
1710         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
1711
1712         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
1713                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
1714                 return rs->sr_err;
1715         }
1716
1717         srs = op->o_controls[slap_cids.sc_LDAPsync];
1718
1719         /* If this is a persistent search, set it up right away */
1720         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
1721                 syncops so = {0};
1722                 fbase_cookie fc;
1723                 opcookie opc;
1724                 slap_callback sc;
1725
1726                 fc.fss = &so;
1727                 fc.fbase = 0;
1728                 so.s_eid = NOID;
1729                 so.s_op = op;
1730                 so.s_flags = PS_IS_REFRESHING;
1731                 /* syncprov_findbase expects to be called as a callback... */
1732                 sc.sc_private = &opc;
1733                 opc.son = on;
1734                 cb = op->o_callback;
1735                 op->o_callback = &sc;
1736                 rs->sr_err = syncprov_findbase( op, &fc );
1737                 op->o_callback = cb;
1738
1739                 if ( rs->sr_err != LDAP_SUCCESS ) {
1740                         send_ldap_result( op, rs );
1741                         return rs->sr_err;
1742                 }
1743                 sop = ch_malloc( sizeof( syncops ));
1744                 *sop = so;
1745                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
1746                 sop->s_rid = srs->sr_state.rid;
1747                 sop->s_inuse = 1;
1748
1749                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1750                 sop->s_next = si->si_ops;
1751                 si->si_ops = sop;
1752                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1753         }
1754
1755         /* snapshot the ctxcsn */
1756         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1757         strcpy( csnbuf, si->si_ctxcsnbuf );
1758         ctxcsn.bv_len = si->si_ctxcsn.bv_len;
1759         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1760         ctxcsn.bv_val = csnbuf;
1761         
1762         /* If we have a cookie, handle the PRESENT lookups */
1763         if ( srs->sr_state.ctxcsn ) {
1764                 sessionlog *sl;
1765
1766                 /* The cookie was validated when it was parsed, just use it */
1767
1768                 /* If just Refreshing and nothing has changed, shortcut it */
1769                 if ( bvmatch( srs->sr_state.ctxcsn, &ctxcsn )) {
1770                         nochange = 1;
1771                         if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
1772                                 LDAPControl     *ctrls[2];
1773
1774                                 ctrls[0] = NULL;
1775                                 ctrls[1] = NULL;
1776                                 syncprov_done_ctrl( op, rs, ctrls, 0, 0,
1777                                         NULL, LDAP_SYNC_REFRESH_DELETES );
1778                                 rs->sr_ctrls = ctrls;
1779                                 rs->sr_err = LDAP_SUCCESS;
1780                                 send_ldap_result( op, rs );
1781                                 rs->sr_ctrls = NULL;
1782                                 return rs->sr_err;
1783                         }
1784                         goto shortcut;
1785                 }
1786                 /* Do we have a sessionlog for this search? */
1787                 sl=si->si_logs;
1788                 if ( sl ) {
1789                         ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
1790                         if ( ber_bvcmp( srs->sr_state.ctxcsn, &sl->sl_mincsn ) >= 0 ) {
1791                                 do_present = 0;
1792                                 /* mutex is unlocked in playlog */
1793                                 syncprov_playlog( op, rs, sl, srs->sr_state.ctxcsn, &ctxcsn );
1794                         } else {
1795                                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1796                         }
1797                 }
1798                 /* Is the CSN still present in the database? */
1799                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
1800                         /* No, so a reload is required */
1801 #if 0           /* the consumer doesn't seem to send this hint */
1802                         if ( op->o_sync_rhint == 0 ) {
1803                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
1804                                 return rs->sr_err;
1805                         }
1806 #endif
1807                 } else {
1808                         gotstate = 1;
1809                         /* If changed and doing Present lookup, send Present UUIDs */
1810                         if ( do_present && syncprov_findcsn( op, FIND_PRESENT ) !=
1811                                 LDAP_SUCCESS ) {
1812                                 send_ldap_result( op, rs );
1813                                 return rs->sr_err;
1814                         }
1815                 }
1816         }
1817
1818 shortcut:
1819         /* Append CSN range to search filter, save original filter
1820          * for persistent search evaluation
1821          */
1822         if ( sop ) {
1823                 sop->s_filterstr= op->ors_filterstr;
1824         }
1825
1826         fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1827         fand->f_choice = LDAP_FILTER_AND;
1828         fand->f_next = NULL;
1829         fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1830         fava->f_choice = LDAP_FILTER_LE;
1831         fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1832         fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1833         ber_dupbv_x( &fava->f_ava->aa_value, &ctxcsn, op->o_tmpmemctx );
1834         fand->f_and = fava;
1835         if ( gotstate ) {
1836                 fava->f_next = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
1837                 fava = fava->f_next;
1838                 fava->f_choice = LDAP_FILTER_GE;
1839                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
1840                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
1841                 ber_dupbv_x( &fava->f_ava->aa_value, srs->sr_state.ctxcsn, op->o_tmpmemctx );
1842         }
1843         fava->f_next = op->ors_filter;
1844         op->ors_filter = fand;
1845         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
1846
1847         /* Let our callback add needed info to returned entries */
1848         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
1849         ss = (searchstate *)(cb+1);
1850         ss->ss_on = on;
1851         ss->ss_so = sop;
1852         ss->ss_present = do_present;
1853         cb->sc_response = syncprov_search_response;
1854         cb->sc_cleanup = syncprov_search_cleanup;
1855         cb->sc_private = ss;
1856         cb->sc_next = op->o_callback;
1857         op->o_callback = cb;
1858
1859 #if 0   /* I don't think we need to shortcircuit back-bdb any more */
1860         op->o_sync_mode &= SLAP_CONTROL_MASK;
1861 #endif
1862
1863         /* If this is a persistent search and no changes were reported during
1864          * the refresh phase, just invoke the response callback to transition
1865          * us into persist phase
1866          */
1867         if ( nochange ) {
1868                 rs->sr_err = LDAP_SUCCESS;
1869                 rs->sr_nentries = 0;
1870                 send_ldap_result( op, rs );
1871                 return rs->sr_err;
1872         }
1873         return SLAP_CB_CONTINUE;
1874 }
1875
1876 static int
1877 syncprov_operational(
1878         Operation *op,
1879         SlapReply *rs )
1880 {
1881         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1882         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1883
1884         if ( rs->sr_entry &&
1885                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
1886
1887                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
1888                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
1889                         Attribute *a, **ap = NULL;
1890
1891                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
1892                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
1893                                         break;
1894                         }
1895
1896                         if ( !a ) {
1897                                 for ( ap = &rs->sr_operational_attrs; *ap; ap=&(*ap)->a_next );
1898
1899                                 a = ch_malloc( sizeof(Attribute));
1900                                 a->a_desc = slap_schema.si_ad_contextCSN;
1901                                 a->a_vals = ch_malloc( 2 * sizeof(struct berval));
1902                                 a->a_vals[1].bv_val = NULL;
1903                                 a->a_nvals = a->a_vals;
1904                                 a->a_next = NULL;
1905                                 a->a_flags = 0;
1906                                 *ap = a;
1907                         }
1908
1909                         ldap_pvt_thread_mutex_lock( &si->si_csn_mutex );
1910                         if ( !ap ) {
1911                                 strcpy( a->a_vals[0].bv_val, si->si_ctxcsnbuf );
1912                         } else {
1913                                 ber_dupbv( &a->a_vals[0], &si->si_ctxcsn );
1914                         }
1915                         ldap_pvt_thread_mutex_unlock( &si->si_csn_mutex );
1916                 }
1917         }
1918         return SLAP_CB_CONTINUE;
1919 }
1920
1921 static int
1922 syncprov_db_config(
1923         BackendDB       *be,
1924         const char      *fname,
1925         int             lineno,
1926         int             argc,
1927         char    **argv
1928 )
1929 {
1930         slap_overinst           *on = (slap_overinst *)be->bd_info;
1931         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
1932
1933         if ( strcasecmp( argv[ 0 ], "syncprov-checkpoint" ) == 0 ) {
1934                 if ( argc != 3 ) {
1935                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1936                                 "\"syncprov-checkpoint <ops> <minutes>\"\n", fname, lineno );
1937                         return -1;
1938                 }
1939                 si->si_chkops = atoi( argv[1] );
1940                 si->si_chktime = atoi( argv[2] ) * 60;
1941                 return 0;
1942
1943         } else if ( strcasecmp( argv[0], "syncprov-sessionlog" ) == 0 ) {
1944                 sessionlog *sl;
1945                 int size;
1946                 if ( argc != 2 ) {
1947                         fprintf( stderr, "%s: line %d: wrong number of arguments in "
1948                                 "\"syncprov-sessionlog <size>\"\n", fname, lineno );
1949                         return -1;
1950                 }
1951                 size = atoi( argv[1] );
1952                 if ( size < 0 ) {
1953                         fprintf( stderr,
1954                                 "%s: line %d: session log size %d is negative\n",
1955                                 fname, lineno, size );
1956                         return -1;
1957                 }
1958                 sl = si->si_logs;
1959                 if ( !sl ) {
1960                         sl = ch_malloc( sizeof( sessionlog ) + LDAP_LUTIL_CSNSTR_BUFSIZE );
1961                         sl->sl_mincsn.bv_val = (char *)(sl+1);
1962                         sl->sl_mincsn.bv_len = 0;
1963                         sl->sl_num = 0;
1964                         sl->sl_head = sl->sl_tail = NULL;
1965                         ldap_pvt_thread_mutex_init( &sl->sl_mutex );
1966                         si->si_logs = sl;
1967                 }
1968                 sl->sl_size = size;
1969                 return 0;
1970         }
1971
1972         return SLAP_CONF_UNKNOWN;
1973 }
1974
1975 /* Cheating - we have no thread pool context for these functions,
1976  * so make one.
1977  */
1978 typedef struct thread_keys {
1979         void *key;
1980         void *data;
1981         ldap_pvt_thread_pool_keyfree_t *xfree;
1982 } thread_keys;
1983
1984 #define MAXKEYS 32
1985 /* A fake thread context */
1986 static thread_keys thrctx[MAXKEYS];
1987
1988 /* Read any existing contextCSN from the underlying db.
1989  * Then search for any entries newer than that. If no value exists,
1990  * just generate it. Cache whatever result.
1991  */
1992 static int
1993 syncprov_db_open(
1994     BackendDB *be
1995 )
1996 {
1997         slap_overinst   *on = (slap_overinst *) be->bd_info;
1998         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1999
2000         Connection conn;
2001         char opbuf[OPERATION_BUFFER_SIZE];
2002         char ctxcsnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
2003         Operation *op = (Operation *)opbuf;
2004         Entry *e;
2005         Attribute *a;
2006         int rc;
2007
2008         connection_fake_init( &conn, op, thrctx );
2009         op->o_bd = be;
2010         op->o_dn = be->be_rootdn;
2011         op->o_ndn = be->be_rootndn;
2012
2013         ctxcsnbuf[0] = '\0';
2014
2015         op->o_bd->bd_info = on->on_info->oi_orig;
2016         rc = be_entry_get_rw( op, be->be_nsuffix, NULL,
2017                 slap_schema.si_ad_contextCSN, 0, &e );
2018
2019         if ( e ) {
2020                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
2021                 if ( a ) {
2022                         si->si_ctxcsn.bv_len = a->a_nvals[0].bv_len;
2023                         if ( si->si_ctxcsn.bv_len >= sizeof(si->si_ctxcsnbuf ))
2024                                 si->si_ctxcsn.bv_len = sizeof(si->si_ctxcsnbuf)-1;
2025                         strncpy( si->si_ctxcsnbuf, a->a_nvals[0].bv_val,
2026                                 si->si_ctxcsn.bv_len );
2027                         si->si_ctxcsnbuf[si->si_ctxcsn.bv_len] = '\0';
2028                         strcpy( ctxcsnbuf, si->si_ctxcsnbuf );
2029                 }
2030                 be_entry_release_rw( op, e, 0 );
2031                 op->o_bd->bd_info = (BackendInfo *)on;
2032                 op->o_req_dn = be->be_suffix[0];
2033                 op->o_req_ndn = be->be_nsuffix[0];
2034                 op->ors_scope = LDAP_SCOPE_SUBTREE;
2035                 syncprov_findcsn( op, FIND_MAXCSN );
2036         }
2037
2038         if ( BER_BVISEMPTY( &si->si_ctxcsn ) ) {
2039                 slap_get_csn( op, si->si_ctxcsnbuf, sizeof(si->si_ctxcsnbuf),
2040                                 &si->si_ctxcsn, 0 );
2041         }
2042
2043         /* If our ctxcsn is different from what was read from the root
2044          * entry, write the new value out.
2045          */
2046         if ( strcmp( si->si_ctxcsnbuf, ctxcsnbuf )) {
2047                 SlapReply rs = {REP_RESULT};
2048                 syncprov_checkpoint( op, &rs, on );
2049         }
2050
2051         op->o_bd->bd_info = (BackendInfo *)on;
2052         return 0;
2053 }
2054
2055 /* Write the current contextCSN into the underlying db.
2056  */
2057 static int
2058 syncprov_db_close(
2059     BackendDB *be
2060 )
2061 {
2062     slap_overinst   *on = (slap_overinst *) be->bd_info;
2063     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2064         int i;
2065
2066         if ( si->si_numops ) {
2067                 Connection conn;
2068                 char opbuf[OPERATION_BUFFER_SIZE];
2069                 Operation *op = (Operation *)opbuf;
2070                 SlapReply rs = {REP_RESULT};
2071
2072                 connection_fake_init( &conn, op, thrctx );
2073                 op->o_bd = be;
2074                 op->o_dn = be->be_rootdn;
2075                 op->o_ndn = be->be_rootndn;
2076                 syncprov_checkpoint( op, &rs, on );
2077         }
2078         for ( i=0; thrctx[i].key; i++) {
2079                 if ( thrctx[i].xfree )
2080                         thrctx[i].xfree( thrctx[i].key, thrctx[i].data );
2081                 thrctx[i].key = NULL;
2082         }
2083
2084     return 0;
2085 }
2086
2087 static int
2088 syncprov_db_init(
2089         BackendDB *be
2090 )
2091 {
2092         slap_overinst   *on = (slap_overinst *)be->bd_info;
2093         syncprov_info_t *si;
2094
2095         si = ch_calloc(1, sizeof(syncprov_info_t));
2096         on->on_bi.bi_private = si;
2097         ldap_pvt_thread_mutex_init( &si->si_csn_mutex );
2098         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
2099         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
2100         si->si_ctxcsn.bv_val = si->si_ctxcsnbuf;
2101
2102         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
2103         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
2104
2105         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
2106         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2107
2108         return 0;
2109 }
2110
2111 static int
2112 syncprov_db_destroy(
2113         BackendDB *be
2114 )
2115 {
2116         slap_overinst   *on = (slap_overinst *)be->bd_info;
2117         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2118
2119         if ( si ) {
2120                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
2121                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
2122                 ldap_pvt_thread_mutex_destroy( &si->si_csn_mutex );
2123                 ch_free( si );
2124         }
2125
2126         return 0;
2127 }
2128
2129 static int syncprov_parseCtrl (
2130         Operation *op,
2131         SlapReply *rs,
2132         LDAPControl *ctrl )
2133 {
2134         ber_tag_t tag;
2135         BerElement *ber;
2136         ber_int_t mode;
2137         ber_len_t len;
2138         struct berval cookie = BER_BVNULL;
2139         sync_control *sr;
2140         int rhint = 0;
2141
2142         if ( op->o_sync != SLAP_CONTROL_NONE ) {
2143                 rs->sr_text = "Sync control specified multiple times";
2144                 return LDAP_PROTOCOL_ERROR;
2145         }
2146
2147         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
2148                 rs->sr_text = "Sync control specified with pagedResults control";
2149                 return LDAP_PROTOCOL_ERROR;
2150         }
2151
2152         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
2153                 rs->sr_text = "Sync control value is empty (or absent)";
2154                 return LDAP_PROTOCOL_ERROR;
2155         }
2156
2157         /* Parse the control value
2158          *      syncRequestValue ::= SEQUENCE {
2159          *              mode   ENUMERATED {
2160          *                      -- 0 unused
2161          *                      refreshOnly             (1),
2162          *                      -- 2 reserved
2163          *                      refreshAndPersist       (3)
2164          *              },
2165          *              cookie  syncCookie OPTIONAL
2166          *      }
2167          */
2168
2169         ber = ber_init( &ctrl->ldctl_value );
2170         if( ber == NULL ) {
2171                 rs->sr_text = "internal error";
2172                 return LDAP_OTHER;
2173         }
2174
2175         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
2176                 rs->sr_text = "Sync control : mode decoding error";
2177                 return LDAP_PROTOCOL_ERROR;
2178         }
2179
2180         switch( mode ) {
2181         case LDAP_SYNC_REFRESH_ONLY:
2182                 mode = SLAP_SYNC_REFRESH;
2183                 break;
2184         case LDAP_SYNC_REFRESH_AND_PERSIST:
2185                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
2186                 break;
2187         default:
2188                 rs->sr_text = "Sync control : unknown update mode";
2189                 return LDAP_PROTOCOL_ERROR;
2190         }
2191
2192         tag = ber_peek_tag( ber, &len );
2193
2194         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
2195                 if (( ber_scanf( ber, /*{*/ "o", &cookie )) == LBER_ERROR ) {
2196                         rs->sr_text = "Sync control : cookie decoding error";
2197                         return LDAP_PROTOCOL_ERROR;
2198                 }
2199         }
2200         if ( tag == LDAP_TAG_RELOAD_HINT ) {
2201                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
2202                         rs->sr_text = "Sync control : rhint decoding error";
2203                         return LDAP_PROTOCOL_ERROR;
2204                 }
2205         }
2206         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
2207                         rs->sr_text = "Sync control : decoding error";
2208                         return LDAP_PROTOCOL_ERROR;
2209         }
2210         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
2211         sr->sr_rhint = rhint;
2212         if (!BER_BVISNULL(&cookie)) {
2213                 ber_bvarray_add( &sr->sr_state.octet_str, &cookie );
2214                 slap_parse_sync_cookie( &sr->sr_state );
2215         }
2216
2217         op->o_controls[slap_cids.sc_LDAPsync] = sr;
2218
2219         (void) ber_free( ber, 1 );
2220
2221         op->o_sync = ctrl->ldctl_iscritical
2222                 ? SLAP_CONTROL_CRITICAL
2223                 : SLAP_CONTROL_NONCRITICAL;
2224
2225         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
2226
2227         return LDAP_SUCCESS;
2228 }
2229
2230 /* This overlay is set up for dynamic loading via moduleload. For static
2231  * configuration, you'll need to arrange for the slap_overinst to be
2232  * initialized and registered by some other function inside slapd.
2233  */
2234
2235 static slap_overinst            syncprov;
2236
2237 int
2238 syncprov_init()
2239 {
2240         int rc;
2241
2242         rc = register_supported_control( LDAP_CONTROL_SYNC,
2243                 SLAP_CTRL_HIDE|SLAP_CTRL_SEARCH, NULL,
2244                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
2245         if ( rc != LDAP_SUCCESS ) {
2246                 fprintf( stderr, "Failed to register control %d\n", rc );
2247                 return rc;
2248         }
2249
2250         syncprov.on_bi.bi_type = "syncprov";
2251         syncprov.on_bi.bi_db_init = syncprov_db_init;
2252         syncprov.on_bi.bi_db_config = syncprov_db_config;
2253         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
2254         syncprov.on_bi.bi_db_open = syncprov_db_open;
2255         syncprov.on_bi.bi_db_close = syncprov_db_close;
2256
2257         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
2258         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
2259
2260         syncprov.on_bi.bi_op_add = syncprov_op_mod;
2261         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
2262         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
2263         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
2264         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
2265         syncprov.on_bi.bi_op_search = syncprov_op_search;
2266         syncprov.on_bi.bi_extended = syncprov_op_extended;
2267         syncprov.on_bi.bi_operational = syncprov_operational;
2268
2269         return overlay_register( &syncprov );
2270 }
2271
2272 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
2273 int
2274 init_module( int argc, char *argv[] )
2275 {
2276         return syncprov_init();
2277 }
2278 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
2279
2280 #endif /* defined(SLAPD_OVER_SYNCPROV) */