]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/syncprov.c
Pull in ITS#5973 code again
[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-2009 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 #include "config.h"
29 #include "ldap_rq.h"
30
31 #ifdef LDAP_DEVEL
32 #define CHECK_CSN       1
33 #endif
34
35 /* A modify request on a particular entry */
36 typedef struct modinst {
37         struct modinst *mi_next;
38         Operation *mi_op;
39 } modinst;
40
41 typedef struct modtarget {
42         struct modinst *mt_mods;
43         struct modinst *mt_tail;
44         Operation *mt_op;
45         ldap_pvt_thread_mutex_t mt_mutex;
46 } modtarget;
47
48 /* A queued result of a persistent search */
49 typedef struct syncres {
50         struct syncres *s_next;
51         struct berval s_dn;
52         struct berval s_ndn;
53         struct berval s_uuid;
54         struct berval s_csn;
55         char s_mode;
56         char s_isreference;
57 } syncres;
58
59 /* Record of a persistent search */
60 typedef struct syncops {
61         struct syncops *s_next;
62         struct berval   s_base;         /* ndn of search base */
63         ID              s_eid;          /* entryID of search base */
64         Operation       *s_op;          /* search op */
65         int             s_rid;
66         int             s_sid;
67         struct berval s_filterstr;
68         int             s_flags;        /* search status */
69 #define PS_IS_REFRESHING        0x01
70 #define PS_IS_DETACHED          0x02
71 #define PS_WROTE_BASE           0x04
72 #define PS_FIND_BASE            0x08
73 #define PS_FIX_FILTER           0x10
74 #define PS_TASK_QUEUED          0x20
75
76         int             s_inuse;        /* reference count */
77         struct syncres *s_res;
78         struct syncres *s_restail;
79         ldap_pvt_thread_mutex_t s_mutex;
80 } syncops;
81
82 /* A received sync control */
83 typedef struct sync_control {
84         struct sync_cookie sr_state;
85         int sr_rhint;
86 } sync_control;
87
88 #if 0 /* moved back to slap.h */
89 #define o_sync  o_ctrlflag[slap_cids.sc_LDAPsync]
90 #endif
91 /* o_sync_mode uses data bits of o_sync */
92 #define o_sync_mode     o_ctrlflag[slap_cids.sc_LDAPsync]
93
94 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
95 #define SLAP_SYNC_REFRESH                               (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
96 #define SLAP_SYNC_PERSIST                               (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
97 #define SLAP_SYNC_REFRESH_AND_PERSIST   (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
98
99 /* Record of which searches matched at premodify step */
100 typedef struct syncmatches {
101         struct syncmatches *sm_next;
102         syncops *sm_op;
103 } syncmatches;
104
105 /* Session log data */
106 typedef struct slog_entry {
107         struct slog_entry *se_next;
108         struct berval se_uuid;
109         struct berval se_csn;
110         int     se_sid;
111         ber_tag_t       se_tag;
112 } slog_entry;
113
114 typedef struct sessionlog {
115         struct berval   sl_mincsn;
116         int             sl_num;
117         int             sl_size;
118         slog_entry *sl_head;
119         slog_entry *sl_tail;
120         ldap_pvt_thread_mutex_t sl_mutex;
121 } sessionlog;
122
123 /* The main state for this overlay */
124 typedef struct syncprov_info_t {
125         syncops         *si_ops;
126         BerVarray       si_ctxcsn;      /* ldapsync context */
127         int             *si_sids;
128         int             si_numcsns;
129         int             si_chkops;      /* checkpointing info */
130         int             si_chktime;
131         int             si_numops;      /* number of ops since last checkpoint */
132         int             si_nopres;      /* Skip present phase */
133         int             si_usehint;     /* use reload hint */
134         time_t  si_chklast;     /* time of last checkpoint */
135         Avlnode *si_mods;       /* entries being modified */
136         sessionlog      *si_logs;
137         ldap_pvt_thread_rdwr_t  si_csn_rwlock;
138         ldap_pvt_thread_mutex_t si_ops_mutex;
139         ldap_pvt_thread_mutex_t si_mods_mutex;
140 } syncprov_info_t;
141
142 typedef struct opcookie {
143         slap_overinst *son;
144         syncmatches *smatches;
145         struct berval sdn;      /* DN of entry, for deletes */
146         struct berval sndn;
147         struct berval suuid;    /* UUID of entry */
148         struct berval sctxcsn;
149         short osid;     /* sid of op csn */
150         short rsid;     /* sid of relay */
151         short sreference;       /* Is the entry a reference? */
152 } opcookie;
153
154 typedef struct fbase_cookie {
155         struct berval *fdn;     /* DN of a modified entry, for scope testing */
156         syncops *fss;   /* persistent search we're testing against */
157         int fbase;      /* if TRUE we found the search base and it's still valid */
158         int fscope;     /* if TRUE then fdn is within the psearch scope */
159 } fbase_cookie;
160
161 static AttributeName csn_anlist[3];
162 static AttributeName uuid_anlist[2];
163
164 /* Build a LDAPsync intermediate state control */
165 static int
166 syncprov_state_ctrl(
167         Operation       *op,
168         SlapReply       *rs,
169         Entry           *e,
170         int             entry_sync_state,
171         LDAPControl     **ctrls,
172         int             num_ctrls,
173         int             send_cookie,
174         struct berval   *cookie )
175 {
176         Attribute* a;
177         int ret;
178
179         BerElementBuffer berbuf;
180         BerElement *ber = (BerElement *)&berbuf;
181
182         struct berval   entryuuid_bv = BER_BVNULL;
183
184         ber_init2( ber, 0, LBER_USE_DER );
185         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
186
187         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
188
189         for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
190                 AttributeDescription *desc = a->a_desc;
191                 if ( desc == slap_schema.si_ad_entryUUID ) {
192                         entryuuid_bv = a->a_nvals[0];
193                         break;
194                 }
195         }
196
197         /* FIXME: what if entryuuid is NULL or empty ? */
198
199         if ( send_cookie && cookie ) {
200                 ber_printf( ber, "{eOON}",
201                         entry_sync_state, &entryuuid_bv, cookie );
202         } else {
203                 ber_printf( ber, "{eON}",
204                         entry_sync_state, &entryuuid_bv );
205         }
206
207         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
208         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
209         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
210
211         ber_free_buf( ber );
212
213         if ( ret < 0 ) {
214                 Debug( LDAP_DEBUG_TRACE,
215                         "slap_build_sync_ctrl: ber_flatten2 failed\n",
216                         0, 0, 0 );
217                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
218                 return ret;
219         }
220
221         return LDAP_SUCCESS;
222 }
223
224 /* Build a LDAPsync final state control */
225 static int
226 syncprov_done_ctrl(
227         Operation       *op,
228         SlapReply       *rs,
229         LDAPControl     **ctrls,
230         int                     num_ctrls,
231         int                     send_cookie,
232         struct berval *cookie,
233         int                     refreshDeletes )
234 {
235         int ret;
236         BerElementBuffer berbuf;
237         BerElement *ber = (BerElement *)&berbuf;
238
239         ber_init2( ber, NULL, LBER_USE_DER );
240         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
241
242         ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
243
244         ber_printf( ber, "{" );
245         if ( send_cookie && cookie ) {
246                 ber_printf( ber, "O", cookie );
247         }
248         if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
249                 ber_printf( ber, "b", refreshDeletes );
250         }
251         ber_printf( ber, "N}" );
252
253         ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
254         ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
255         ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
256
257         ber_free_buf( ber );
258
259         if ( ret < 0 ) {
260                 Debug( LDAP_DEBUG_TRACE,
261                         "syncprov_done_ctrl: ber_flatten2 failed\n",
262                         0, 0, 0 );
263                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
264                 return ret;
265         }
266
267         return LDAP_SUCCESS;
268 }
269
270 static int
271 syncprov_sendinfo(
272         Operation       *op,
273         SlapReply       *rs,
274         int                     type,
275         struct berval *cookie,
276         int                     refreshDone,
277         BerVarray       syncUUIDs,
278         int                     refreshDeletes )
279 {
280         BerElementBuffer berbuf;
281         BerElement *ber = (BerElement *)&berbuf;
282         struct berval rspdata;
283
284         int ret;
285
286         ber_init2( ber, NULL, LBER_USE_DER );
287         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
288
289         if ( type ) {
290                 switch ( type ) {
291                 case LDAP_TAG_SYNC_NEW_COOKIE:
292                         ber_printf( ber, "tO", type, cookie );
293                         break;
294                 case LDAP_TAG_SYNC_REFRESH_DELETE:
295                 case LDAP_TAG_SYNC_REFRESH_PRESENT:
296                         ber_printf( ber, "t{", type );
297                         if ( cookie ) {
298                                 ber_printf( ber, "O", cookie );
299                         }
300                         if ( refreshDone == 0 ) {
301                                 ber_printf( ber, "b", refreshDone );
302                         }
303                         ber_printf( ber, "N}" );
304                         break;
305                 case LDAP_TAG_SYNC_ID_SET:
306                         ber_printf( ber, "t{", type );
307                         if ( cookie ) {
308                                 ber_printf( ber, "O", cookie );
309                         }
310                         if ( refreshDeletes == 1 ) {
311                                 ber_printf( ber, "b", refreshDeletes );
312                         }
313                         ber_printf( ber, "[W]", syncUUIDs );
314                         ber_printf( ber, "N}" );
315                         break;
316                 default:
317                         Debug( LDAP_DEBUG_TRACE,
318                                 "syncprov_sendinfo: invalid syncinfo type (%d)\n",
319                                 type, 0, 0 );
320                         return LDAP_OTHER;
321                 }
322         }
323
324         ret = ber_flatten2( ber, &rspdata, 0 );
325
326         if ( ret < 0 ) {
327                 Debug( LDAP_DEBUG_TRACE,
328                         "syncprov_sendinfo: ber_flatten2 failed\n",
329                         0, 0, 0 );
330                 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
331                 return ret;
332         }
333
334         rs->sr_rspoid = LDAP_SYNC_INFO;
335         rs->sr_rspdata = &rspdata;
336         send_ldap_intermediate( op, rs );
337         rs->sr_rspdata = NULL;
338         ber_free_buf( ber );
339
340         return LDAP_SUCCESS;
341 }
342
343 /* Find a modtarget in an AVL tree */
344 static int
345 sp_avl_cmp( const void *c1, const void *c2 )
346 {
347         const modtarget *m1, *m2;
348         int rc;
349
350         m1 = c1; m2 = c2;
351         rc = m1->mt_op->o_req_ndn.bv_len - m2->mt_op->o_req_ndn.bv_len;
352
353         if ( rc ) return rc;
354         return ber_bvcmp( &m1->mt_op->o_req_ndn, &m2->mt_op->o_req_ndn );
355 }
356
357 /* syncprov_findbase:
358  *   finds the true DN of the base of a search (with alias dereferencing) and
359  * checks to make sure the base entry doesn't get replaced with a different
360  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
361  * change is detected, any persistent search on this base must be terminated /
362  * reloaded.
363  *   On the first call, we just save the DN and entryID. On subsequent calls
364  * we compare the DN and entryID with the saved values.
365  */
366 static int
367 findbase_cb( Operation *op, SlapReply *rs )
368 {
369         slap_callback *sc = op->o_callback;
370
371         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
372                 fbase_cookie *fc = sc->sc_private;
373
374                 /* If no entryID, we're looking for the first time.
375                  * Just store whatever we got.
376                  */
377                 if ( fc->fss->s_eid == NOID ) {
378                         fc->fbase = 2;
379                         fc->fss->s_eid = rs->sr_entry->e_id;
380                         ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
381
382                 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
383                         dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
384
385                 /* OK, the DN is the same and the entryID is the same. */
386                         fc->fbase = 1;
387                 }
388         }
389         if ( rs->sr_err != LDAP_SUCCESS ) {
390                 Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err,0,0 );
391         }
392         return LDAP_SUCCESS;
393 }
394
395 static Filter generic_filter = { LDAP_FILTER_PRESENT, { 0 }, NULL };
396 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
397
398 static int
399 syncprov_findbase( Operation *op, fbase_cookie *fc )
400 {
401         /* Use basic parameters from syncrepl search, but use
402          * current op's threadctx / tmpmemctx
403          */
404         ldap_pvt_thread_mutex_lock( &fc->fss->s_mutex );
405         if ( fc->fss->s_flags & PS_FIND_BASE ) {
406                 slap_callback cb = {0};
407                 Operation fop;
408                 SlapReply frs = { REP_RESULT };
409                 int rc;
410
411                 fc->fss->s_flags ^= PS_FIND_BASE;
412                 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
413
414                 fop = *fc->fss->s_op;
415
416                 fop.o_bd = fop.o_bd->bd_self;
417                 fop.o_hdr = op->o_hdr;
418                 fop.o_time = op->o_time;
419                 fop.o_tincr = op->o_tincr;
420
421                 cb.sc_response = findbase_cb;
422                 cb.sc_private = fc;
423
424                 fop.o_sync_mode = 0;    /* turn off sync mode */
425                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
426                 fop.o_callback = &cb;
427                 fop.o_tag = LDAP_REQ_SEARCH;
428                 fop.ors_scope = LDAP_SCOPE_BASE;
429                 fop.ors_limit = NULL;
430                 fop.ors_slimit = 1;
431                 fop.ors_tlimit = SLAP_NO_LIMIT;
432                 fop.ors_attrs = slap_anlist_no_attrs;
433                 fop.ors_attrsonly = 1;
434                 fop.ors_filter = &generic_filter;
435                 fop.ors_filterstr = generic_filterstr;
436
437                 rc = fop.o_bd->be_search( &fop, &frs );
438         } else {
439                 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
440                 fc->fbase = 1;
441         }
442
443         /* After the first call, see if the fdn resides in the scope */
444         if ( fc->fbase == 1 ) {
445                 switch ( fc->fss->s_op->ors_scope ) {
446                 case LDAP_SCOPE_BASE:
447                         fc->fscope = dn_match( fc->fdn, &fc->fss->s_base );
448                         break;
449                 case LDAP_SCOPE_ONELEVEL: {
450                         struct berval pdn;
451                         dnParent( fc->fdn, &pdn );
452                         fc->fscope = dn_match( &pdn, &fc->fss->s_base );
453                         break; }
454                 case LDAP_SCOPE_SUBTREE:
455                         fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base );
456                         break;
457                 case LDAP_SCOPE_SUBORDINATE:
458                         fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base ) &&
459                                 !dn_match( fc->fdn, &fc->fss->s_base );
460                         break;
461                 }
462         }
463
464         if ( fc->fbase )
465                 return LDAP_SUCCESS;
466
467         /* If entryID has changed, then the base of this search has
468          * changed. Invalidate the psearch.
469          */
470         return LDAP_NO_SUCH_OBJECT;
471 }
472
473 /* syncprov_findcsn:
474  *   This function has three different purposes, but they all use a search
475  * that filters on entryCSN so they're combined here.
476  * 1: at startup time, after a contextCSN has been read from the database,
477  * we search for all entries with CSN >= contextCSN in case the contextCSN
478  * was not checkpointed at the previous shutdown.
479  *
480  * 2: when the current contextCSN is known and we have a sync cookie, we search
481  * for one entry with CSN = the cookie CSN. If not found, try <= cookie CSN.
482  * If an entry is found, the cookie CSN is valid, otherwise it is stale.
483  *
484  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
485  * CSN, and generate Present records for them. We always collect this result
486  * in SyncID sets, even if there's only one match.
487  */
488 typedef enum find_csn_t {
489         FIND_MAXCSN     = 1,
490         FIND_CSN        = 2,
491         FIND_PRESENT    = 3
492 } find_csn_t;
493
494 static int
495 findmax_cb( Operation *op, SlapReply *rs )
496 {
497         if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
498                 struct berval *maxcsn = op->o_callback->sc_private;
499                 Attribute *a = attr_find( rs->sr_entry->e_attrs,
500                         slap_schema.si_ad_entryCSN );
501
502                 if ( a && ber_bvcmp( &a->a_vals[0], maxcsn ) > 0 &&
503                         slap_parse_csn_sid( &a->a_vals[0] ) == slap_serverID ) {
504                         maxcsn->bv_len = a->a_vals[0].bv_len;
505                         strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
506                 }
507         }
508         return LDAP_SUCCESS;
509 }
510
511 static int
512 findcsn_cb( Operation *op, SlapReply *rs )
513 {
514         slap_callback *sc = op->o_callback;
515
516         /* We just want to know that at least one exists, so it's OK if
517          * we exceed the unchecked limit.
518          */
519         if ( rs->sr_err == LDAP_ADMINLIMIT_EXCEEDED ||
520                 (rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS )) {
521                 sc->sc_private = (void *)1;
522         }
523         return LDAP_SUCCESS;
524 }
525
526 /* Build a list of entryUUIDs for sending in a SyncID set */
527
528 #define UUID_LEN        16
529
530 typedef struct fpres_cookie {
531         int num;
532         BerVarray uuids;
533         char *last;
534 } fpres_cookie;
535
536 static int
537 findpres_cb( Operation *op, SlapReply *rs )
538 {
539         slap_callback *sc = op->o_callback;
540         fpres_cookie *pc = sc->sc_private;
541         Attribute *a;
542         int ret = SLAP_CB_CONTINUE;
543
544         switch ( rs->sr_type ) {
545         case REP_SEARCH:
546                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
547                 if ( a ) {
548                         pc->uuids[pc->num].bv_val = pc->last;
549                         AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
550                                 pc->uuids[pc->num].bv_len );
551                         pc->num++;
552                         pc->last = pc->uuids[pc->num].bv_val;
553                         pc->uuids[pc->num].bv_val = NULL;
554                 }
555                 ret = LDAP_SUCCESS;
556                 if ( pc->num != SLAP_SYNCUUID_SET_SIZE )
557                         break;
558                 /* FALLTHRU */
559         case REP_RESULT:
560                 ret = rs->sr_err;
561                 if ( pc->num ) {
562                         ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
563                                 0, pc->uuids, 0 );
564                         pc->uuids[pc->num].bv_val = pc->last;
565                         pc->num = 0;
566                         pc->last = pc->uuids[0].bv_val;
567                 }
568                 break;
569         default:
570                 break;
571         }
572         return ret;
573 }
574
575 static int
576 syncprov_findcsn( Operation *op, find_csn_t mode )
577 {
578         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
579         syncprov_info_t         *si = on->on_bi.bi_private;
580
581         slap_callback cb = {0};
582         Operation fop;
583         SlapReply frs = { REP_RESULT };
584         char buf[LDAP_LUTIL_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
585         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
586         struct berval maxcsn;
587         Filter cf;
588         AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
589         fpres_cookie pcookie;
590         sync_control *srs = NULL;
591         struct slap_limits_set fc_limits;
592         int i, rc = LDAP_SUCCESS, findcsn_retry = 1;
593         int maxid;
594
595         if ( mode != FIND_MAXCSN ) {
596                 srs = op->o_controls[slap_cids.sc_LDAPsync];
597         }
598
599         fop = *op;
600         fop.o_sync_mode &= SLAP_CONTROL_MASK;   /* turn off sync_mode */
601         /* We want pure entries, not referrals */
602         fop.o_managedsait = SLAP_CONTROL_CRITICAL;
603
604         cf.f_ava = &eq;
605         cf.f_av_desc = slap_schema.si_ad_entryCSN;
606         BER_BVZERO( &cf.f_av_value );
607         cf.f_next = NULL;
608
609         fop.o_callback = &cb;
610         fop.ors_limit = NULL;
611         fop.ors_tlimit = SLAP_NO_LIMIT;
612         fop.ors_filter = &cf;
613         fop.ors_filterstr.bv_val = buf;
614
615 again:
616         switch( mode ) {
617         case FIND_MAXCSN:
618                 cf.f_choice = LDAP_FILTER_GE;
619                 /* If there are multiple CSNs, use the one with our serverID */
620                 for ( i=0; i<si->si_numcsns; i++) {
621                         if ( slap_serverID == si->si_sids[i] ) {
622                                 maxid = i;
623                                 break;
624                         }
625                 }
626                 if ( i == si->si_numcsns ) {
627                         /* No match: this is multimaster, and none of the content in the DB
628                          * originated locally. Treat like no CSN.
629                          */
630                         return LDAP_NO_SUCH_OBJECT;
631                 }
632                 cf.f_av_value = si->si_ctxcsn[maxid];
633                 fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
634                         "(entryCSN>=%s)", cf.f_av_value.bv_val );
635                 if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
636                         return LDAP_OTHER;
637                 }
638                 fop.ors_attrsonly = 0;
639                 fop.ors_attrs = csn_anlist;
640                 fop.ors_slimit = SLAP_NO_LIMIT;
641                 cb.sc_private = &maxcsn;
642                 cb.sc_response = findmax_cb;
643                 strcpy( cbuf, cf.f_av_value.bv_val );
644                 maxcsn.bv_val = cbuf;
645                 maxcsn.bv_len = cf.f_av_value.bv_len;
646                 break;
647         case FIND_CSN:
648                 if ( BER_BVISEMPTY( &cf.f_av_value )) {
649                         cf.f_av_value = srs->sr_state.ctxcsn[0];
650                         /* If there are multiple CSNs, use the smallest */
651                         for ( i=1; i<srs->sr_state.numcsns; i++ ) {
652                                 if ( ber_bvcmp( &cf.f_av_value, &srs->sr_state.ctxcsn[i] )
653                                         > 0 ) {
654                                         cf.f_av_value = srs->sr_state.ctxcsn[i];
655                                 }
656                         }
657                 }
658                 /* Look for exact match the first time */
659                 if ( findcsn_retry ) {
660                         cf.f_choice = LDAP_FILTER_EQUALITY;
661                         fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
662                                 "(entryCSN=%s)", cf.f_av_value.bv_val );
663                 /* On retry, look for <= */
664                 } else {
665                         cf.f_choice = LDAP_FILTER_LE;
666                         fop.ors_limit = &fc_limits;
667                         memset( &fc_limits, 0, sizeof( fc_limits ));
668                         fc_limits.lms_s_unchecked = 1;
669                         fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
670                                 "(entryCSN<=%s)", cf.f_av_value.bv_val );
671                 }
672                 if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
673                         return LDAP_OTHER;
674                 }
675                 fop.ors_attrsonly = 1;
676                 fop.ors_attrs = slap_anlist_no_attrs;
677                 fop.ors_slimit = 1;
678                 cb.sc_private = NULL;
679                 cb.sc_response = findcsn_cb;
680                 break;
681         case FIND_PRESENT:
682                 fop.ors_filter = op->ors_filter;
683                 fop.ors_filterstr = op->ors_filterstr;
684                 fop.ors_attrsonly = 0;
685                 fop.ors_attrs = uuid_anlist;
686                 fop.ors_slimit = SLAP_NO_LIMIT;
687                 cb.sc_private = &pcookie;
688                 cb.sc_response = findpres_cb;
689                 pcookie.num = 0;
690
691                 /* preallocate storage for a full set */
692                 pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
693                         sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
694                         op->o_tmpmemctx );
695                 pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
696                 pcookie.uuids[0].bv_val = pcookie.last;
697                 pcookie.uuids[0].bv_len = UUID_LEN;
698                 for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
699                         pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
700                         pcookie.uuids[i].bv_len = UUID_LEN;
701                 }
702                 break;
703         }
704
705         fop.o_bd->bd_info = (BackendInfo *)on->on_info;
706         fop.o_bd->be_search( &fop, &frs );
707         fop.o_bd->bd_info = (BackendInfo *)on;
708
709         switch( mode ) {
710         case FIND_MAXCSN:
711                 if ( ber_bvcmp( &si->si_ctxcsn[maxid], &maxcsn )) {
712 #ifdef CHECK_CSN
713                         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
714                         assert( !syn->ssyn_validate( syn, &maxcsn ));
715 #endif
716                         ber_bvreplace( &si->si_ctxcsn[maxid], &maxcsn );
717                         si->si_numops++;        /* ensure a checkpoint */
718                 }
719                 break;
720         case FIND_CSN:
721                 /* If matching CSN was not found, invalidate the context. */
722                 if ( !cb.sc_private ) {
723                         /* If we didn't find an exact match, then try for <= */
724                         if ( findcsn_retry ) {
725                                 findcsn_retry = 0;
726                                 goto again;
727                         }
728                         rc = LDAP_NO_SUCH_OBJECT;
729                 }
730                 break;
731         case FIND_PRESENT:
732                 op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
733                 break;
734         }
735
736         return rc;
737 }
738
739 static void
740 syncprov_free_syncop( syncops *so )
741 {
742         syncres *sr, *srnext;
743         GroupAssertion *ga, *gnext;
744
745         ldap_pvt_thread_mutex_lock( &so->s_mutex );
746         if ( --so->s_inuse > 0 ) {
747                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
748                 return;
749         }
750         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
751         if ( so->s_flags & PS_IS_DETACHED ) {
752                 filter_free( so->s_op->ors_filter );
753                 for ( ga = so->s_op->o_groups; ga; ga=gnext ) {
754                         gnext = ga->ga_next;
755                         ch_free( ga );
756                 }
757                 ch_free( so->s_op );
758         }
759         ch_free( so->s_base.bv_val );
760         for ( sr=so->s_res; sr; sr=srnext ) {
761                 srnext = sr->s_next;
762                 ch_free( sr );
763         }
764         ldap_pvt_thread_mutex_destroy( &so->s_mutex );
765         ch_free( so );
766 }
767
768 /* Send a persistent search response */
769 static int
770 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so,
771         Entry **e, int mode )
772 {
773         slap_overinst *on = opc->son;
774
775         SlapReply rs = { REP_SEARCH };
776         LDAPControl *ctrls[2];
777         struct berval cookie, csns[2];
778         Entry e_uuid = {0};
779         Attribute a_uuid = {0};
780
781         if ( so->s_op->o_abandon )
782                 return SLAPD_ABANDON;
783
784         ctrls[1] = NULL;
785         csns[0] = opc->sctxcsn;
786         BER_BVZERO( &csns[1] );
787         slap_compose_sync_cookie( op, &cookie, csns, so->s_rid, slap_serverID ? slap_serverID : -1 );
788
789 #ifdef LDAP_DEBUG
790         if ( so->s_sid > 0 ) {
791                 Debug( LDAP_DEBUG_SYNC, "syncprov_sendresp: to=%03x, cookie=%s\n",
792                         so->s_sid, cookie.bv_val, 0 );
793         } else {
794                 Debug( LDAP_DEBUG_SYNC, "syncprov_sendresp: cookie=%s\n",
795                         cookie.bv_val, 0, 0 );
796         }
797 #endif
798
799         e_uuid.e_attrs = &a_uuid;
800         a_uuid.a_desc = slap_schema.si_ad_entryUUID;
801         a_uuid.a_nvals = &opc->suuid;
802         rs.sr_err = syncprov_state_ctrl( op, &rs, &e_uuid,
803                 mode, ctrls, 0, 1, &cookie );
804         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
805
806         rs.sr_ctrls = ctrls;
807         op->o_bd->bd_info = (BackendInfo *)on->on_info;
808         switch( mode ) {
809         case LDAP_SYNC_ADD:
810                 rs.sr_entry = *e;
811                 if ( rs.sr_entry->e_private )
812                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
813                 if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
814                         rs.sr_ref = get_entry_referrals( op, rs.sr_entry );
815                         rs.sr_err = send_search_reference( op, &rs );
816                         ber_bvarray_free( rs.sr_ref );
817                         if ( !rs.sr_entry )
818                                 *e = NULL;
819                         break;
820                 }
821                 /* fallthru */
822         case LDAP_SYNC_MODIFY:
823                 rs.sr_entry = *e;
824                 if ( rs.sr_entry->e_private )
825                         rs.sr_flags = REP_ENTRY_MUSTRELEASE;
826                 rs.sr_attrs = op->ors_attrs;
827                 rs.sr_err = send_search_entry( op, &rs );
828                 if ( !rs.sr_entry )
829                         *e = NULL;
830                 break;
831         case LDAP_SYNC_DELETE:
832                 e_uuid.e_attrs = NULL;
833                 e_uuid.e_name = opc->sdn;
834                 e_uuid.e_nname = opc->sndn;
835                 rs.sr_entry = &e_uuid;
836                 if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
837                         struct berval bv = BER_BVNULL;
838                         rs.sr_ref = &bv;
839                         rs.sr_err = send_search_reference( op, &rs );
840                 } else {
841                         rs.sr_err = send_search_entry( op, &rs );
842                 }
843                 break;
844         default:
845                 assert(0);
846         }
847         /* In case someone else freed it already? */
848         if ( rs.sr_ctrls ) {
849                 op->o_tmpfree( rs.sr_ctrls[0], op->o_tmpmemctx );
850                 rs.sr_ctrls = NULL;
851         }
852
853         return rs.sr_err;
854 }
855
856 static void
857 syncprov_qstart( syncops *so );
858
859 /* Play back queued responses */
860 static int
861 syncprov_qplay( Operation *op, syncops *so )
862 {
863         slap_overinst *on = LDAP_SLIST_FIRST(&so->s_op->o_extra)->oe_key;
864         syncres *sr;
865         Entry *e;
866         opcookie opc;
867         int rc = 0;
868
869         opc.son = on;
870
871         do {
872                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
873                 sr = so->s_res;
874                 if ( sr )
875                         so->s_res = sr->s_next;
876                 if ( !so->s_res )
877                         so->s_restail = NULL;
878                 /* Exit loop with mutex held */
879                 if ( !sr || so->s_op->o_abandon )
880                         break;
881                 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
882
883                 if ( sr->s_mode == LDAP_SYNC_NEW_COOKIE ) {
884                     SlapReply rs = { REP_INTERMEDIATE };
885
886                     rc = syncprov_sendinfo( op, &rs, LDAP_TAG_SYNC_NEW_COOKIE,
887                                 &sr->s_csn, 0, NULL, 0 );
888                 } else {
889                         opc.sdn = sr->s_dn;
890                         opc.sndn = sr->s_ndn;
891                         opc.suuid = sr->s_uuid;
892                         opc.sctxcsn = sr->s_csn;
893                         opc.sreference = sr->s_isreference;
894                         e = NULL;
895
896                         if ( sr->s_mode != LDAP_SYNC_DELETE ) {
897                                 rc = overlay_entry_get_ov( op, &opc.sndn, NULL, NULL, 0, &e, on );
898                                 if ( rc ) {
899                                         Debug( LDAP_DEBUG_SYNC, "syncprov_qplay: failed to get %s, "
900                                                 "error (%d), ignoring...\n", opc.sndn.bv_val, rc, 0 );
901                                         ch_free( sr );
902                                         rc = 0;
903                                         continue;
904                                 }
905                         }
906                         rc = syncprov_sendresp( op, &opc, so, &e, sr->s_mode );
907
908                         if ( e ) {
909                                 overlay_entry_release_ov( op, e, 0, on );
910                         }
911                 }
912
913                 ch_free( sr );
914
915                 /* Exit loop with mutex held */
916                 ldap_pvt_thread_mutex_lock( &so->s_mutex );
917
918         } while (0);
919
920         /* We now only send one change at a time, to prevent one
921          * psearch from hogging all the CPU. Resubmit this task if
922          * there are more responses queued and no errors occurred.
923          */
924
925         if ( rc == 0 && so->s_res ) {
926                 syncprov_qstart( so );
927         } else {
928                 so->s_flags ^= PS_TASK_QUEUED;
929         }
930
931         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
932         return rc;
933 }
934
935 /* task for playing back queued responses */
936 static void *
937 syncprov_qtask( void *ctx, void *arg )
938 {
939         syncops *so = arg;
940         OperationBuffer opbuf;
941         Operation *op;
942         BackendDB be;
943         int rc;
944
945         op = &opbuf.ob_op;
946         *op = *so->s_op;
947         op->o_hdr = &opbuf.ob_hdr;
948         op->o_controls = opbuf.ob_controls;
949         memset( op->o_controls, 0, sizeof(opbuf.ob_controls) );
950
951         *op->o_hdr = *so->s_op->o_hdr;
952
953         op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx, 1);
954         op->o_tmpmfuncs = &slap_sl_mfuncs;
955         op->o_threadctx = ctx;
956
957         /* syncprov_qplay expects a fake db */
958         be = *so->s_op->o_bd;
959         be.be_flags |= SLAP_DBFLAG_OVERLAY;
960         op->o_bd = &be;
961         LDAP_SLIST_FIRST(&op->o_extra) = NULL;
962         op->o_callback = NULL;
963
964         rc = syncprov_qplay( op, so );
965
966         /* decrement use count... */
967         syncprov_free_syncop( so );
968
969         return NULL;
970 }
971
972 /* Start the task to play back queued psearch responses */
973 static void
974 syncprov_qstart( syncops *so )
975 {
976         so->s_flags |= PS_TASK_QUEUED;
977         so->s_inuse++;
978         ldap_pvt_thread_pool_submit( &connection_pool, 
979                 syncprov_qtask, so );
980 }
981
982 /* Queue a persistent search response */
983 static int
984 syncprov_qresp( opcookie *opc, syncops *so, int mode )
985 {
986         syncres *sr;
987         int srsize;
988         struct berval cookie = opc->sctxcsn;
989
990         if ( mode == LDAP_SYNC_NEW_COOKIE ) {
991                 syncprov_info_t *si = opc->son->on_bi.bi_private;
992
993                 slap_compose_sync_cookie( NULL, &cookie, si->si_ctxcsn,
994                         so->s_rid, slap_serverID ? slap_serverID : -1);
995         }
996
997         srsize = sizeof(syncres) + opc->suuid.bv_len + 1 +
998                 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1;
999         if ( cookie.bv_len )
1000                 srsize += cookie.bv_len + 1;
1001         sr = ch_malloc( srsize );
1002         sr->s_next = NULL;
1003         sr->s_dn.bv_val = (char *)(sr + 1);
1004         sr->s_dn.bv_len = opc->sdn.bv_len;
1005         sr->s_mode = mode;
1006         sr->s_isreference = opc->sreference;
1007         sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val,
1008                  opc->sdn.bv_val ) + 1;
1009         sr->s_ndn.bv_len = opc->sndn.bv_len;
1010         sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val,
1011                  opc->sndn.bv_val ) + 1;
1012         sr->s_uuid.bv_len = opc->suuid.bv_len;
1013         AC_MEMCPY( sr->s_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1014         if ( cookie.bv_len ) {
1015                 sr->s_csn.bv_val = sr->s_uuid.bv_val + sr->s_uuid.bv_len + 1;
1016                 strcpy( sr->s_csn.bv_val, cookie.bv_val );
1017         } else {
1018                 sr->s_csn.bv_val = NULL;
1019         }
1020         sr->s_csn.bv_len = cookie.bv_len;
1021
1022         if ( mode == LDAP_SYNC_NEW_COOKIE && cookie.bv_val ) {
1023                 ch_free( cookie.bv_val );
1024         }
1025
1026         ldap_pvt_thread_mutex_lock( &so->s_mutex );
1027         if ( !so->s_res ) {
1028                 so->s_res = sr;
1029         } else {
1030                 so->s_restail->s_next = sr;
1031         }
1032         so->s_restail = sr;
1033
1034         /* If the base of the psearch was modified, check it next time round */
1035         if ( so->s_flags & PS_WROTE_BASE ) {
1036                 so->s_flags ^= PS_WROTE_BASE;
1037                 so->s_flags |= PS_FIND_BASE;
1038         }
1039         if (( so->s_flags & (PS_IS_DETACHED|PS_TASK_QUEUED)) == PS_IS_DETACHED ) {
1040                 syncprov_qstart( so );
1041         }
1042         ldap_pvt_thread_mutex_unlock( &so->s_mutex );
1043         return LDAP_SUCCESS;
1044 }
1045
1046 static int
1047 syncprov_drop_psearch( syncops *so, int lock )
1048 {
1049         if ( so->s_flags & PS_IS_DETACHED ) {
1050                 if ( lock )
1051                         ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
1052                 so->s_op->o_conn->c_n_ops_executing--;
1053                 so->s_op->o_conn->c_n_ops_completed++;
1054                 LDAP_STAILQ_REMOVE( &so->s_op->o_conn->c_ops, so->s_op, Operation,
1055                         o_next );
1056                 if ( lock )
1057                         ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
1058         }
1059         syncprov_free_syncop( so );
1060
1061         return 0;
1062 }
1063
1064 static int
1065 syncprov_ab_cleanup( Operation *op, SlapReply *rs )
1066 {
1067         slap_callback *sc = op->o_callback;
1068         op->o_callback = sc->sc_next;
1069         syncprov_drop_psearch( op->o_callback->sc_private, 0 );
1070         op->o_tmpfree( sc, op->o_tmpmemctx );
1071         return 0;
1072 }
1073
1074 static int
1075 syncprov_op_abandon( Operation *op, SlapReply *rs )
1076 {
1077         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1078         syncprov_info_t         *si = on->on_bi.bi_private;
1079         syncops *so, *soprev;
1080
1081         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1082         for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
1083                 soprev=so, so=so->s_next ) {
1084                 if ( so->s_op->o_connid == op->o_connid &&
1085                         so->s_op->o_msgid == op->orn_msgid ) {
1086                                 so->s_op->o_abandon = 1;
1087                                 soprev->s_next = so->s_next;
1088                                 break;
1089                 }
1090         }
1091         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1092         if ( so ) {
1093                 /* Is this really a Cancel exop? */
1094                 if ( op->o_tag != LDAP_REQ_ABANDON ) {
1095                         so->s_op->o_cancel = SLAP_CANCEL_ACK;
1096                         rs->sr_err = LDAP_CANCELLED;
1097                         send_ldap_result( so->s_op, rs );
1098                         if ( so->s_flags & PS_IS_DETACHED ) {
1099                                 slap_callback *cb;
1100                                 cb = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1101                                 cb->sc_cleanup = syncprov_ab_cleanup;
1102                                 cb->sc_next = op->o_callback;
1103                                 cb->sc_private = so;
1104                                 return SLAP_CB_CONTINUE;
1105                         }
1106                 }
1107                 syncprov_drop_psearch( so, 0 );
1108         }
1109         return SLAP_CB_CONTINUE;
1110 }
1111
1112 /* Find which persistent searches are affected by this operation */
1113 static void
1114 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
1115 {
1116         slap_overinst *on = opc->son;
1117         syncprov_info_t         *si = on->on_bi.bi_private;
1118
1119         fbase_cookie fc;
1120         syncops *ss, *sprev, *snext;
1121         Entry *e = NULL;
1122         Attribute *a;
1123         int rc;
1124         struct berval newdn;
1125         int freefdn = 0;
1126         BackendDB *b0 = op->o_bd, db;
1127
1128         fc.fdn = &op->o_req_ndn;
1129         /* compute new DN */
1130         if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1131                 struct berval pdn;
1132                 if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
1133                 else dnParent( fc.fdn, &pdn );
1134                 build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
1135                 fc.fdn = &newdn;
1136                 freefdn = 1;
1137         }
1138         if ( op->o_tag != LDAP_REQ_ADD ) {
1139                 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1140                         db = *op->o_bd;
1141                         op->o_bd = &db;
1142                 }
1143                 rc = overlay_entry_get_ov( op, fc.fdn, NULL, NULL, 0, &e, on );
1144                 /* If we're sending responses now, make a copy and unlock the DB */
1145                 if ( e && !saveit ) {
1146                         Entry *e2 = entry_dup( e );
1147                         overlay_entry_release_ov( op, e, 0, on );
1148                         e = e2;
1149                 }
1150                 if ( rc ) {
1151                         op->o_bd = b0;
1152                         return;
1153                 }
1154         } else {
1155                 e = op->ora_e;
1156         }
1157
1158         if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
1159                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1160                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1161                 opc->sreference = is_entry_referral( e );
1162                 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
1163                 if ( a )
1164                         ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
1165         } else if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
1166                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1167                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1168                 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1169                 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1170         }
1171
1172         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1173         for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
1174                 sprev = ss, ss=snext)
1175         {
1176                 Operation op2;
1177                 Opheader oh;
1178                 syncmatches *sm;
1179                 int found = 0;
1180
1181                 snext = ss->s_next;
1182                 if ( ss->s_op->o_abandon )
1183                         continue;
1184
1185                 /* First time thru, check for possible skips */
1186                 if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
1187
1188                         /* Don't send ops back to the originator */
1189                         if ( opc->osid > 0 && opc->osid == ss->s_sid ) {
1190                                 Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping original sid %03x\n",
1191                                         opc->osid, 0, 0 );
1192                                 continue;
1193                         }
1194
1195                         /* Don't send ops back to the messenger */
1196                         if ( opc->rsid > 0 && opc->rsid == ss->s_sid ) {
1197                                 Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping relayed sid %03x\n",
1198                                         opc->rsid, 0, 0 );
1199                                 continue;
1200                         }
1201                 }
1202
1203                 /* validate base */
1204                 fc.fss = ss;
1205                 fc.fbase = 0;
1206                 fc.fscope = 0;
1207
1208                 /* If the base of the search is missing, signal a refresh */
1209                 rc = syncprov_findbase( op, &fc );
1210                 if ( rc != LDAP_SUCCESS ) {
1211                         SlapReply rs = {REP_RESULT};
1212                         send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
1213                                 "search base has changed" );
1214                         sprev->s_next = snext;
1215                         syncprov_drop_psearch( ss, 1 );
1216                         ss = sprev;
1217                         continue;
1218                 }
1219
1220
1221                 /* If we're sending results now, look for this op in old matches */
1222                 if ( !saveit ) {
1223                         syncmatches *old;
1224
1225                         /* Did we modify the search base? */
1226                         if ( dn_match( &op->o_req_ndn, &ss->s_base )) {
1227                                 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1228                                 ss->s_flags |= PS_WROTE_BASE;
1229                                 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1230                         }
1231
1232                         for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
1233                                 old=sm, sm=sm->sm_next ) {
1234                                 if ( sm->sm_op == ss ) {
1235                                         found = 1;
1236                                         old->sm_next = sm->sm_next;
1237                                         op->o_tmpfree( sm, op->o_tmpmemctx );
1238                                         break;
1239                                 }
1240                         }
1241                 }
1242
1243                 if ( fc.fscope ) {
1244                         op2 = *ss->s_op;
1245                         oh = *op->o_hdr;
1246                         oh.oh_conn = ss->s_op->o_conn;
1247                         oh.oh_connid = ss->s_op->o_connid;
1248                         op2.o_hdr = &oh;
1249                         op2.o_extra = op->o_extra;
1250                         rc = test_filter( &op2, e, ss->s_op->ors_filter );
1251                 }
1252
1253                 Debug( LDAP_DEBUG_TRACE, "syncprov_matchops: sid %03x fscope %d rc %d\n",
1254                         ss->s_sid, fc.fscope, rc );
1255
1256                 /* check if current o_req_dn is in scope and matches filter */
1257                 if ( fc.fscope && rc == LDAP_COMPARE_TRUE ) {
1258                         if ( saveit ) {
1259                                 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
1260                                 sm->sm_next = opc->smatches;
1261                                 sm->sm_op = ss;
1262                                 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1263                                 ++ss->s_inuse;
1264                                 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1265                                 opc->smatches = sm;
1266                         } else {
1267                                 /* if found send UPDATE else send ADD */
1268                                 syncprov_qresp( opc, ss,
1269                                         found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD );
1270                         }
1271                 } else if ( !saveit && found ) {
1272                         /* send DELETE */
1273                         syncprov_qresp( opc, ss, LDAP_SYNC_DELETE );
1274                 } else if ( !saveit ) {
1275                         syncprov_qresp( opc, ss, LDAP_SYNC_NEW_COOKIE );
1276                 }
1277                 if ( !saveit && found ) {
1278                         /* Decrement s_inuse, was incremented when called
1279                          * with saveit == TRUE
1280                          */
1281                         syncprov_free_syncop( ss );
1282                 }
1283         }
1284         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1285
1286         if ( op->o_tag != LDAP_REQ_ADD && e ) {
1287                 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1288                         op->o_bd = &db;
1289                 }
1290                 overlay_entry_release_ov( op, e, 0, on );
1291                 op->o_bd = b0;
1292         }
1293         if ( freefdn ) {
1294                 op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
1295         }
1296         op->o_bd = b0;
1297 }
1298
1299 static int
1300 syncprov_op_cleanup( Operation *op, SlapReply *rs )
1301 {
1302         slap_callback *cb = op->o_callback;
1303         opcookie *opc = cb->sc_private;
1304         slap_overinst *on = opc->son;
1305         syncprov_info_t         *si = on->on_bi.bi_private;
1306         syncmatches *sm, *snext;
1307         modtarget *mt, mtdummy;
1308
1309         for (sm = opc->smatches; sm; sm=snext) {
1310                 snext = sm->sm_next;
1311                 syncprov_free_syncop( sm->sm_op );
1312                 op->o_tmpfree( sm, op->o_tmpmemctx );
1313         }
1314
1315         /* Remove op from lock table */
1316         mtdummy.mt_op = op;
1317         ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1318         mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1319         if ( mt ) {
1320                 modinst *mi = mt->mt_mods;
1321
1322                 /* If there are more, promote the next one */
1323                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1324                 if ( mi->mi_next ) {
1325                         mt->mt_mods = mi->mi_next;
1326                         mt->mt_op = mt->mt_mods->mi_op;
1327                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1328                 } else {
1329                         avl_delete( &si->si_mods, mt, sp_avl_cmp );
1330                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1331                         ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1332                         ch_free( mt );
1333                 }
1334         }
1335         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1336         if ( !BER_BVISNULL( &opc->suuid ))
1337                 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1338         if ( !BER_BVISNULL( &opc->sndn ))
1339                 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1340         if ( !BER_BVISNULL( &opc->sdn ))
1341                 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1342         op->o_callback = cb->sc_next;
1343         op->o_tmpfree(cb, op->o_tmpmemctx);
1344
1345         return 0;
1346 }
1347
1348 static void
1349 syncprov_checkpoint( Operation *op, SlapReply *rs, slap_overinst *on )
1350 {
1351         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1352         Modifications mod;
1353         Operation opm;
1354         SlapReply rsm = { 0 };
1355         slap_callback cb = {0};
1356         BackendDB be;
1357 #ifdef CHECK_CSN
1358         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
1359
1360         int i;
1361         for ( i=0; i<si->si_numcsns; i++ ) {
1362                 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1363         }
1364 #endif
1365         mod.sml_numvals = si->si_numcsns;
1366         mod.sml_values = si->si_ctxcsn;
1367         mod.sml_nvalues = NULL;
1368         mod.sml_desc = slap_schema.si_ad_contextCSN;
1369         mod.sml_op = LDAP_MOD_REPLACE;
1370         mod.sml_flags = SLAP_MOD_INTERNAL;
1371         mod.sml_next = NULL;
1372
1373         cb.sc_response = slap_null_cb;
1374         opm = *op;
1375         opm.o_tag = LDAP_REQ_MODIFY;
1376         opm.o_callback = &cb;
1377         opm.orm_modlist = &mod;
1378         opm.orm_no_opattrs = 1;
1379         if ( SLAP_GLUE_SUBORDINATE( op->o_bd )) {
1380                 be = *on->on_info->oi_origdb;
1381                 opm.o_bd = &be;
1382         }
1383         opm.o_req_dn = opm.o_bd->be_suffix[0];
1384         opm.o_req_ndn = opm.o_bd->be_nsuffix[0];
1385         opm.o_bd->bd_info = on->on_info->oi_orig;
1386         opm.o_managedsait = SLAP_CONTROL_NONCRITICAL;
1387         opm.o_no_schema_check = 1;
1388         opm.o_bd->be_modify( &opm, &rsm );
1389         if ( mod.sml_next != NULL ) {
1390                 slap_mods_free( mod.sml_next, 1 );
1391         }
1392 #ifdef CHECK_CSN
1393         for ( i=0; i<si->si_numcsns; i++ ) {
1394                 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1395         }
1396 #endif
1397 }
1398
1399 static void
1400 syncprov_add_slog( Operation *op )
1401 {
1402         opcookie *opc = op->o_callback->sc_private;
1403         slap_overinst *on = opc->son;
1404         syncprov_info_t         *si = on->on_bi.bi_private;
1405         sessionlog *sl;
1406         slog_entry *se;
1407
1408         sl = si->si_logs;
1409         {
1410                 /* Allocate a record. UUIDs are not NUL-terminated. */
1411                 se = ch_malloc( sizeof( slog_entry ) + opc->suuid.bv_len + 
1412                         op->o_csn.bv_len + 1 );
1413                 se->se_next = NULL;
1414                 se->se_tag = op->o_tag;
1415
1416                 se->se_uuid.bv_val = (char *)(&se[1]);
1417                 AC_MEMCPY( se->se_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1418                 se->se_uuid.bv_len = opc->suuid.bv_len;
1419
1420                 se->se_csn.bv_val = se->se_uuid.bv_val + opc->suuid.bv_len;
1421                 AC_MEMCPY( se->se_csn.bv_val, op->o_csn.bv_val, op->o_csn.bv_len );
1422                 se->se_csn.bv_val[op->o_csn.bv_len] = '\0';
1423                 se->se_csn.bv_len = op->o_csn.bv_len;
1424                 se->se_sid = slap_parse_csn_sid( &se->se_csn );
1425
1426                 ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
1427                 if ( sl->sl_head ) {
1428                         sl->sl_tail->se_next = se;
1429                 } else {
1430                         sl->sl_head = se;
1431                 }
1432                 sl->sl_tail = se;
1433                 sl->sl_num++;
1434                 while ( sl->sl_num > sl->sl_size ) {
1435                         se = sl->sl_head;
1436                         sl->sl_head = se->se_next;
1437                         strcpy( sl->sl_mincsn.bv_val, se->se_csn.bv_val );
1438                         sl->sl_mincsn.bv_len = se->se_csn.bv_len;
1439                         ch_free( se );
1440                         sl->sl_num--;
1441                 }
1442                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1443         }
1444 }
1445
1446 /* Just set a flag if we found the matching entry */
1447 static int
1448 playlog_cb( Operation *op, SlapReply *rs )
1449 {
1450         if ( rs->sr_type == REP_SEARCH ) {
1451                 op->o_callback->sc_private = (void *)1;
1452         }
1453         return rs->sr_err;
1454 }
1455
1456 /* enter with sl->sl_mutex locked, release before returning */
1457 static void
1458 syncprov_playlog( Operation *op, SlapReply *rs, sessionlog *sl,
1459         sync_control *srs, BerVarray ctxcsn, int numcsns, int *sids )
1460 {
1461         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1462         slog_entry *se;
1463         int i, j, ndel, num, nmods, mmods;
1464         char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1465         BerVarray uuids;
1466         struct berval delcsn[2];
1467
1468         if ( !sl->sl_num ) {
1469                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1470                 return;
1471         }
1472
1473         num = sl->sl_num;
1474         i = 0;
1475         nmods = 0;
1476
1477         uuids = op->o_tmpalloc( (num+1) * sizeof( struct berval ) +
1478                 num * UUID_LEN, op->o_tmpmemctx );
1479         uuids[0].bv_val = (char *)(uuids + num + 1);
1480
1481         delcsn[0].bv_len = 0;
1482         delcsn[0].bv_val = cbuf;
1483         BER_BVZERO(&delcsn[1]);
1484
1485         /* Make a copy of the relevant UUIDs. Put the Deletes up front
1486          * and everything else at the end. Do this first so we can
1487          * unlock the list mutex.
1488          */
1489         Debug( LDAP_DEBUG_SYNC, "srs csn %s\n",
1490                 srs->sr_state.ctxcsn[0].bv_val, 0, 0 );
1491         for ( se=sl->sl_head; se; se=se->se_next ) {
1492                 int k;
1493                 Debug( LDAP_DEBUG_SYNC, "log csn %s\n", se->se_csn.bv_val, 0, 0 );
1494                 ndel = 1;
1495                 for ( k=0; k<srs->sr_state.numcsns; k++ ) {
1496                         if ( se->se_sid == srs->sr_state.sids[k] ) {
1497                                 ndel = ber_bvcmp( &se->se_csn, &srs->sr_state.ctxcsn[k] );
1498                                 break;
1499                         }
1500                 }
1501                 if ( ndel <= 0 ) {
1502                         Debug( LDAP_DEBUG_SYNC, "cmp %d, too old\n", ndel, 0, 0 );
1503                         continue;
1504                 }
1505                 ndel = 0;
1506                 for ( k=0; k<numcsns; k++ ) {
1507                         if ( se->se_sid == sids[k] ) {
1508                                 ndel = ber_bvcmp( &se->se_csn, &ctxcsn[k] );
1509                                 break;
1510                         }
1511                 }
1512                 if ( ndel > 0 ) {
1513                         Debug( LDAP_DEBUG_SYNC, "cmp %d, too new\n", ndel, 0, 0 );
1514                         break;
1515                 }
1516                 if ( se->se_tag == LDAP_REQ_DELETE ) {
1517                         j = i;
1518                         i++;
1519                         AC_MEMCPY( cbuf, se->se_csn.bv_val, se->se_csn.bv_len );
1520                         delcsn[0].bv_len = se->se_csn.bv_len;
1521                         delcsn[0].bv_val[delcsn[0].bv_len] = '\0';
1522                 } else {
1523                         nmods++;
1524                         j = num - nmods;
1525                 }
1526                 uuids[j].bv_val = uuids[0].bv_val + (j * UUID_LEN);
1527                 AC_MEMCPY(uuids[j].bv_val, se->se_uuid.bv_val, UUID_LEN);
1528                 uuids[j].bv_len = UUID_LEN;
1529         }
1530         ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
1531
1532         ndel = i;
1533
1534         /* Zero out unused slots */
1535         for ( i=ndel; i < num - nmods; i++ )
1536                 uuids[i].bv_len = 0;
1537
1538         /* Mods must be validated to see if they belong in this delete set.
1539          */
1540
1541         mmods = nmods;
1542         /* Strip any duplicates */
1543         for ( i=0; i<nmods; i++ ) {
1544                 for ( j=0; j<ndel; j++ ) {
1545                         if ( bvmatch( &uuids[j], &uuids[num - 1 - i] )) {
1546                                 uuids[num - 1 - i].bv_len = 0;
1547                                 mmods --;
1548                                 break;
1549                         }
1550                 }
1551                 if ( uuids[num - 1 - i].bv_len == 0 ) continue;
1552                 for ( j=0; j<i; j++ ) {
1553                         if ( bvmatch( &uuids[num - 1 - j], &uuids[num - 1 - i] )) {
1554                                 uuids[num - 1 - i].bv_len = 0;
1555                                 mmods --;
1556                                 break;
1557                         }
1558                 }
1559         }
1560
1561         if ( mmods ) {
1562                 Operation fop;
1563                 SlapReply frs = { REP_RESULT };
1564                 int rc;
1565                 Filter mf, af;
1566                 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
1567                 slap_callback cb = {0};
1568
1569                 fop = *op;
1570
1571                 fop.o_sync_mode = 0;
1572                 fop.o_callback = &cb;
1573                 fop.ors_limit = NULL;
1574                 fop.ors_tlimit = SLAP_NO_LIMIT;
1575                 fop.ors_attrs = slap_anlist_all_attributes;
1576                 fop.ors_attrsonly = 0;
1577                 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
1578
1579                 af.f_choice = LDAP_FILTER_AND;
1580                 af.f_next = NULL;
1581                 af.f_and = &mf;
1582                 mf.f_choice = LDAP_FILTER_EQUALITY;
1583                 mf.f_ava = &eq;
1584                 mf.f_av_desc = slap_schema.si_ad_entryUUID;
1585                 mf.f_next = fop.ors_filter;
1586
1587                 fop.ors_filter = &af;
1588
1589                 cb.sc_response = playlog_cb;
1590                 fop.o_bd->bd_info = (BackendInfo *)on->on_info;
1591
1592                 for ( i=ndel; i<num; i++ ) {
1593                         if ( uuids[i].bv_len == 0 ) continue;
1594
1595                         mf.f_av_value = uuids[i];
1596                         cb.sc_private = NULL;
1597                         fop.ors_slimit = 1;
1598                         frs.sr_nentries = 0;
1599                         rc = fop.o_bd->be_search( &fop, &frs );
1600
1601                         /* If entry was not found, add to delete list */
1602                         if ( !cb.sc_private ) {
1603                                 uuids[ndel++] = uuids[i];
1604                         }
1605                 }
1606                 fop.o_bd->bd_info = (BackendInfo *)on;
1607         }
1608         if ( ndel ) {
1609                 struct berval cookie;
1610
1611                 if ( delcsn[0].bv_len ) {
1612                         slap_compose_sync_cookie( op, &cookie, delcsn, srs->sr_state.rid,
1613                                 slap_serverID ? slap_serverID : -1 );
1614
1615                         Debug( LDAP_DEBUG_SYNC, "syncprov_playlog: cookie=%s\n", cookie.bv_val, 0, 0 );
1616                 }
1617
1618                 uuids[ndel].bv_val = NULL;
1619                 syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET,
1620                         delcsn[0].bv_len ? &cookie : NULL, 0, uuids, 1 );
1621                 if ( delcsn[0].bv_len ) {
1622                         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
1623                 }
1624         }
1625         op->o_tmpfree( uuids, op->o_tmpmemctx );
1626 }
1627
1628 static int
1629 syncprov_op_response( Operation *op, SlapReply *rs )
1630 {
1631         opcookie *opc = op->o_callback->sc_private;
1632         slap_overinst *on = opc->son;
1633         syncprov_info_t         *si = on->on_bi.bi_private;
1634         syncmatches *sm;
1635
1636         if ( rs->sr_err == LDAP_SUCCESS )
1637         {
1638                 struct berval maxcsn;
1639                 char cbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1640                 int do_check = 0, have_psearches, foundit, csn_changed = 0;
1641
1642                 /* Update our context CSN */
1643                 cbuf[0] = '\0';
1644                 maxcsn.bv_val = cbuf;
1645                 maxcsn.bv_len = sizeof(cbuf);
1646                 ldap_pvt_thread_rdwr_wlock( &si->si_csn_rwlock );
1647
1648 #if 0
1649                 if ( op->o_dont_replicate &&
1650                                 op->orm_modlist->sml_op == LDAP_MOD_REPLACE &&
1651                                 op->orm_modlist->sml_desc == slap_schema.si_ad_contextCSN ) {
1652                         /* Catch contextCSN updates from syncrepl. We have to look at
1653                          * all the attribute values, as there may be more than one csn
1654                          * that changed, and only one can be passed in the csn queue.
1655                          */
1656                         Modifications *mod = op->orm_modlist;
1657                         int i, j, sid;
1658
1659                         for ( i=0; i<mod->sml_numvals; i++ ) {
1660                                 sid = slap_parse_csn_sid( &mod->sml_values[i] );
1661
1662                                 for ( j=0; j<si->si_numcsns; j++ ) {
1663                                         if ( sid == si->si_sids[j] ) {
1664                                                 if ( ber_bvcmp( &mod->sml_values[i], &si->si_ctxcsn[j] ) > 0 ) {
1665                                                         ber_bvreplace( &si->si_ctxcsn[j], &mod->sml_values[i] );
1666                                                         csn_changed = 1;
1667                                                 }
1668                                                 break;
1669                                         }
1670                                 }
1671
1672                                 if ( j == si->si_numcsns ) {
1673                                         value_add_one( &si->si_ctxcsn, &mod->sml_values[i] );
1674                                         si->si_numcsns++;
1675                                         si->si_sids = ch_realloc( si->si_sids, si->si_numcsns *
1676                                                 sizeof(int));
1677                                         si->si_sids[j] = sid;
1678                                         csn_changed = 1;
1679                                 }
1680                         }
1681                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1682
1683                         if ( csn_changed ) {
1684                                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1685                                 have_psearches = ( si->si_ops != NULL );
1686                                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1687
1688                                 if ( have_psearches ) {
1689                                         for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1690                                                 if ( sm->sm_op->s_op->o_abandon )
1691                                                         continue;
1692                                                 syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_NEW_COOKIE );
1693                                         }
1694                                 }
1695                         }
1696                         return SLAP_CB_CONTINUE;
1697                 }
1698 #endif
1699
1700                 slap_get_commit_csn( op, &maxcsn, &foundit );
1701                 if ( BER_BVISEMPTY( &maxcsn ) && SLAP_GLUE_SUBORDINATE( op->o_bd )) {
1702                         /* syncrepl queues the CSN values in the db where
1703                          * it is configured , not where the changes are made.
1704                          * So look for a value in the glue db if we didn't
1705                          * find any in this db.
1706                          */
1707                         BackendDB *be = op->o_bd;
1708                         op->o_bd = select_backend( &be->be_nsuffix[0], 1);
1709                         maxcsn.bv_val = cbuf;
1710                         maxcsn.bv_len = sizeof(cbuf);
1711                         slap_get_commit_csn( op, &maxcsn, &foundit );
1712                         op->o_bd = be;
1713                 }
1714                 if ( !BER_BVISEMPTY( &maxcsn ) ) {
1715                         int i, sid;
1716 #ifdef CHECK_CSN
1717                         Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
1718                         assert( !syn->ssyn_validate( syn, &maxcsn ));
1719 #endif
1720                         sid = slap_parse_csn_sid( &maxcsn );
1721                         for ( i=0; i<si->si_numcsns; i++ ) {
1722                                 if ( sid == si->si_sids[i] ) {
1723                                         if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn[i] ) > 0 ) {
1724                                                 ber_bvreplace( &si->si_ctxcsn[i], &maxcsn );
1725                                                 csn_changed = 1;
1726                                         }
1727                                         break;
1728                                 }
1729                         }
1730                         /* It's a new SID for us */
1731                         if ( i == si->si_numcsns ) {
1732                                 value_add_one( &si->si_ctxcsn, &maxcsn );
1733                                 csn_changed = 1;
1734                                 si->si_numcsns++;
1735                                 si->si_sids = ch_realloc( si->si_sids, si->si_numcsns *
1736                                         sizeof(int));
1737                                 si->si_sids[i] = sid;
1738                         }
1739                 } else if ( !foundit ) {
1740                         /* internal ops that aren't meant to be replicated */
1741                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1742                         return SLAP_CB_CONTINUE;
1743                 }
1744
1745                 /* Don't do any processing for consumer contextCSN updates */
1746                 if ( op->o_dont_replicate ) {
1747                         ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1748                         return SLAP_CB_CONTINUE;
1749                 }
1750
1751                 si->si_numops++;
1752                 if ( si->si_chkops || si->si_chktime ) {
1753                         if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
1754                                 do_check = 1;
1755                                 si->si_numops = 0;
1756                         }
1757                         if ( si->si_chktime &&
1758                                 (op->o_time - si->si_chklast >= si->si_chktime )) {
1759                                 if ( si->si_chklast ) {
1760                                         do_check = 1;
1761                                         si->si_chklast = op->o_time;
1762                                 } else {
1763                                         si->si_chklast = 1;
1764                                 }
1765                         }
1766                 }
1767                 ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
1768
1769                 if ( do_check ) {
1770                         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
1771                         syncprov_checkpoint( op, rs, on );
1772                         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
1773                 }
1774
1775                 /* only update consumer ctx if this is a newer csn */
1776                 if ( csn_changed ) {
1777                         opc->sctxcsn = maxcsn;
1778                 }
1779
1780                 /* Handle any persistent searches */
1781                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1782                 have_psearches = ( si->si_ops != NULL );
1783                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1784                 if ( have_psearches ) {
1785                         switch(op->o_tag) {
1786                         case LDAP_REQ_ADD:
1787                         case LDAP_REQ_MODIFY:
1788                         case LDAP_REQ_MODRDN:
1789                         case LDAP_REQ_EXTENDED:
1790                                 syncprov_matchops( op, opc, 0 );
1791                                 break;
1792                         case LDAP_REQ_DELETE:
1793                                 /* for each match in opc->smatches:
1794                                  *   send DELETE msg
1795                                  */
1796                                 for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
1797                                         if ( sm->sm_op->s_op->o_abandon )
1798                                                 continue;
1799                                         syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_DELETE );
1800                                 }
1801                                 break;
1802                         }
1803                 }
1804
1805                 /* Add any log records */
1806                 if ( si->si_logs && op->o_tag != LDAP_REQ_ADD ) {
1807                         syncprov_add_slog( op );
1808                 }
1809
1810         }
1811         return SLAP_CB_CONTINUE;
1812 }
1813
1814 /* We don't use a subentry to store the context CSN any more.
1815  * We expose the current context CSN as an operational attribute
1816  * of the suffix entry.
1817  */
1818 static int
1819 syncprov_op_compare( Operation *op, SlapReply *rs )
1820 {
1821         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1822         syncprov_info_t         *si = on->on_bi.bi_private;
1823         int rc = SLAP_CB_CONTINUE;
1824
1825         if ( dn_match( &op->o_req_ndn, op->o_bd->be_nsuffix ) &&
1826                 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
1827         {
1828                 Entry e = {0};
1829                 Attribute a = {0};
1830
1831                 e.e_name = op->o_bd->be_suffix[0];
1832                 e.e_nname = op->o_bd->be_nsuffix[0];
1833                 e.e_attrs = &a;
1834
1835                 a.a_desc = slap_schema.si_ad_contextCSN;
1836
1837                 ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
1838
1839                 a.a_vals = si->si_ctxcsn;
1840                 a.a_nvals = a.a_vals;
1841                 a.a_numvals = si->si_numcsns;
1842
1843                 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
1844                         &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
1845                 if ( ! rs->sr_err ) {
1846                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1847                         goto return_results;
1848                 }
1849
1850                 if ( get_assert( op ) &&
1851                         ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
1852                 {
1853                         rs->sr_err = LDAP_ASSERTION_FAILED;
1854                         goto return_results;
1855                 }
1856
1857
1858                 rs->sr_err = LDAP_COMPARE_FALSE;
1859
1860                 if ( attr_valfind( &a,
1861                         SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
1862                                 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
1863                                 &op->oq_compare.rs_ava->aa_value, NULL, op->o_tmpmemctx ) == 0 )
1864                 {
1865                         rs->sr_err = LDAP_COMPARE_TRUE;
1866                 }
1867
1868 return_results:;
1869
1870                 ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
1871
1872                 send_ldap_result( op, rs );
1873
1874                 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
1875                         rs->sr_err = LDAP_SUCCESS;
1876                 }
1877                 rc = rs->sr_err;
1878         }
1879
1880         return rc;
1881 }
1882
1883 static int
1884 syncprov_op_mod( Operation *op, SlapReply *rs )
1885 {
1886         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1887         syncprov_info_t         *si = on->on_bi.bi_private;
1888         slap_callback *cb;
1889         opcookie *opc;
1890         int have_psearches, cbsize;
1891
1892         ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1893         have_psearches = ( si->si_ops != NULL );
1894         ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1895
1896         cbsize = sizeof(slap_callback) + sizeof(opcookie) +
1897                 (have_psearches ? sizeof(modinst) : 0 );
1898
1899         cb = op->o_tmpcalloc(1, cbsize, op->o_tmpmemctx);
1900         opc = (opcookie *)(cb+1);
1901         opc->son = on;
1902         cb->sc_response = syncprov_op_response;
1903         cb->sc_cleanup = syncprov_op_cleanup;
1904         cb->sc_private = opc;
1905         cb->sc_next = op->o_callback;
1906         op->o_callback = cb;
1907
1908         opc->osid = -1;
1909         opc->rsid = -1;
1910         if ( op->o_csn.bv_val ) {
1911                 opc->osid = slap_parse_csn_sid( &op->o_csn );
1912         }
1913         if ( op->o_controls ) {
1914                 struct sync_cookie *scook =
1915                 op->o_controls[slap_cids.sc_LDAPsync];
1916                 if ( scook )
1917                         opc->rsid = scook->sid;
1918         }
1919
1920         /* If there are active persistent searches, lock this operation.
1921          * See seqmod.c for the locking logic on its own.
1922          */
1923         if ( have_psearches ) {
1924                 modtarget *mt, mtdummy;
1925                 modinst *mi;
1926
1927                 mi = (modinst *)(opc+1);
1928                 mi->mi_op = op;
1929
1930                 /* See if we're already modifying this entry... */
1931                 mtdummy.mt_op = op;
1932                 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1933                 mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
1934                 if ( mt ) {
1935                         ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1936                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1937                         mt->mt_tail->mi_next = mi;
1938                         mt->mt_tail = mi;
1939                         /* wait for this op to get to head of list */
1940                         while ( mt->mt_mods != mi ) {
1941                                 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1942                                 /* FIXME: if dynamic config can delete overlays or
1943                                  * databases we'll have to check for cleanup here.
1944                                  * Currently it's not an issue because there are
1945                                  * no dynamic config deletes...
1946                                  */
1947                                 if ( slapd_shutdown )
1948                                         return SLAPD_ABANDON;
1949
1950                                 if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1951                                         ldap_pvt_thread_yield();
1952                                 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1953
1954                                 /* clean up if the caller is giving up */
1955                                 if ( op->o_abandon ) {
1956                                         modinst *m2;
1957                                         for ( m2 = mt->mt_mods; m2->mi_next != mi;
1958                                                 m2 = m2->mi_next );
1959                                         m2->mi_next = mi->mi_next;
1960                                         if ( mt->mt_tail == mi ) mt->mt_tail = m2;
1961                                         op->o_tmpfree( cb, op->o_tmpmemctx );
1962                                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1963                                         return SLAPD_ABANDON;
1964                                 }
1965                         }
1966                         ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1967                 } else {
1968                         /* Record that we're modifying this entry now */
1969                         mt = ch_malloc( sizeof(modtarget) );
1970                         mt->mt_mods = mi;
1971                         mt->mt_tail = mi;
1972                         mt->mt_op = mi->mi_op;
1973                         ldap_pvt_thread_mutex_init( &mt->mt_mutex );
1974                         avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
1975                         ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1976                 }
1977         }
1978
1979         if (( have_psearches || si->si_logs ) && op->o_tag != LDAP_REQ_ADD )
1980                 syncprov_matchops( op, opc, 1 );
1981
1982         return SLAP_CB_CONTINUE;
1983 }
1984
1985 static int
1986 syncprov_op_extended( Operation *op, SlapReply *rs )
1987 {
1988         if ( exop_is_write( op ))
1989                 return syncprov_op_mod( op, rs );
1990
1991         return SLAP_CB_CONTINUE;
1992 }
1993
1994 typedef struct searchstate {
1995         slap_overinst *ss_on;
1996         syncops *ss_so;
1997         BerVarray ss_ctxcsn;
1998         int *ss_sids;
1999         int ss_numcsns;
2000 #define SS_PRESENT      0x01
2001 #define SS_CHANGED      0x02
2002         int ss_flags;
2003 } searchstate;
2004
2005 static int
2006 syncprov_search_cleanup( Operation *op, SlapReply *rs )
2007 {
2008         if ( rs->sr_ctrls ) {
2009                 op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
2010                 op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
2011                 rs->sr_ctrls = NULL;
2012         }
2013         return 0;
2014 }
2015
2016 typedef struct SyncOperationBuffer {
2017         Operation               sob_op;
2018         Opheader                sob_hdr;
2019         OpExtra                 sob_oe;
2020         AttributeName   sob_extra;      /* not always present */
2021         /* Further data allocated here */
2022 } SyncOperationBuffer;
2023
2024 static void
2025 syncprov_detach_op( Operation *op, syncops *so, slap_overinst *on )
2026 {
2027         SyncOperationBuffer *sopbuf2;
2028         Operation *op2;
2029         int i, alen = 0;
2030         size_t size;
2031         char *ptr;
2032         GroupAssertion *g1, *g2;
2033
2034         /* count the search attrs */
2035         for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2036                 alen += op->ors_attrs[i].an_name.bv_len + 1;
2037         }
2038         /* Make a new copy of the operation */
2039         size = offsetof( SyncOperationBuffer, sob_extra ) +
2040                 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
2041                 op->o_req_dn.bv_len + 1 +
2042                 op->o_req_ndn.bv_len + 1 +
2043                 op->o_ndn.bv_len + 1 +
2044                 so->s_filterstr.bv_len + 1;
2045         sopbuf2 = ch_calloc( 1, size );
2046         op2 = &sopbuf2->sob_op;
2047         op2->o_hdr = &sopbuf2->sob_hdr;
2048         LDAP_SLIST_FIRST(&op2->o_extra) = &sopbuf2->sob_oe;
2049
2050         /* Copy the fields we care about explicitly, leave the rest alone */
2051         *op2->o_hdr = *op->o_hdr;
2052         op2->o_tag = op->o_tag;
2053         op2->o_time = op->o_time;
2054         op2->o_bd = on->on_info->oi_origdb;
2055         op2->o_request = op->o_request;
2056         op2->o_managedsait = op->o_managedsait;
2057         LDAP_SLIST_FIRST(&op2->o_extra)->oe_key = on;
2058         LDAP_SLIST_NEXT(LDAP_SLIST_FIRST(&op2->o_extra), oe_next) = NULL;
2059
2060         ptr = (char *) sopbuf2 + offsetof( SyncOperationBuffer, sob_extra );
2061         if ( i ) {
2062                 op2->ors_attrs = (AttributeName *) ptr;
2063                 ptr = (char *) &op2->ors_attrs[i+1];
2064                 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2065                         op2->ors_attrs[i] = op->ors_attrs[i];
2066                         op2->ors_attrs[i].an_name.bv_val = ptr;
2067                         ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
2068                 }
2069                 BER_BVZERO( &op2->ors_attrs[i].an_name );
2070         }
2071
2072         op2->o_authz = op->o_authz;
2073         op2->o_ndn.bv_val = ptr;
2074         ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
2075         op2->o_dn = op2->o_ndn;
2076         op2->o_req_dn.bv_len = op->o_req_dn.bv_len;
2077         op2->o_req_dn.bv_val = ptr;
2078         ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
2079         op2->o_req_ndn.bv_len = op->o_req_ndn.bv_len;
2080         op2->o_req_ndn.bv_val = ptr;
2081         ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
2082         op2->ors_filterstr.bv_val = ptr;
2083         strcpy( ptr, so->s_filterstr.bv_val );
2084         op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
2085
2086         /* Skip the AND/GE clause that we stuck on in front */
2087         if ( so->s_flags & PS_FIX_FILTER ) {
2088                 op2->ors_filter = op->ors_filter->f_and->f_next;
2089                 so->s_flags ^= PS_FIX_FILTER;
2090         } else {
2091                 op2->ors_filter = op->ors_filter;
2092         }
2093         op2->ors_filter = filter_dup( op2->ors_filter, NULL );
2094         so->s_op = op2;
2095
2096         /* Copy any cached group ACLs individually */
2097         op2->o_groups = NULL;
2098         for ( g1=op->o_groups; g1; g1=g1->ga_next ) {
2099                 g2 = ch_malloc( sizeof(GroupAssertion) + g1->ga_len );
2100                 *g2 = *g1;
2101                 strcpy( g2->ga_ndn, g1->ga_ndn );
2102                 g2->ga_next = op2->o_groups;
2103                 op2->o_groups = g2;
2104         }
2105         /* Don't allow any further group caching */
2106         op2->o_do_not_cache = 1;
2107
2108         /* Add op2 to conn so abandon will find us */
2109         op->o_conn->c_n_ops_executing++;
2110         op->o_conn->c_n_ops_completed--;
2111         LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op2, o_next );
2112         so->s_flags |= PS_IS_DETACHED;
2113
2114         /* Prevent anyone else from trying to send a result for this op */
2115         op->o_abandon = 1;
2116 }
2117
2118 static int
2119 syncprov_search_response( Operation *op, SlapReply *rs )
2120 {
2121         searchstate *ss = op->o_callback->sc_private;
2122         slap_overinst *on = ss->ss_on;
2123         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2124         sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
2125
2126         if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
2127                 Attribute *a;
2128                 /* If we got a referral without a referral object, there's
2129                  * something missing that we cannot replicate. Just ignore it.
2130                  * The consumer will abort because we didn't send the expected
2131                  * control.
2132                  */
2133                 if ( !rs->sr_entry ) {
2134                         assert( rs->sr_entry != NULL );
2135                         Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
2136                         return SLAP_CB_CONTINUE;
2137                 }
2138                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryCSN );
2139                 if ( a == NULL && rs->sr_operational_attrs != NULL ) {
2140                         a = attr_find( rs->sr_operational_attrs, slap_schema.si_ad_entryCSN );
2141                 }
2142                 if ( a ) {
2143                         int i, sid;
2144                         sid = slap_parse_csn_sid( &a->a_nvals[0] );
2145
2146                         /* Don't send changed entries back to the originator */
2147                         if ( sid == srs->sr_state.sid && srs->sr_state.numcsns ) {
2148                                 Debug( LDAP_DEBUG_SYNC,
2149                                         "Entry %s changed by peer, ignored\n",
2150                                         rs->sr_entry->e_name.bv_val, 0, 0 );
2151                                 return LDAP_SUCCESS;
2152                         }
2153
2154                         /* If not a persistent search */
2155                         if ( !ss->ss_so ) {
2156                                 /* Make sure entry is less than the snapshot'd contextCSN */
2157                                 for ( i=0; i<ss->ss_numcsns; i++ ) {
2158                                         if ( sid == ss->ss_sids[i] && ber_bvcmp( &a->a_nvals[0],
2159                                                 &ss->ss_ctxcsn[i] ) > 0 ) {
2160                                                 Debug( LDAP_DEBUG_SYNC,
2161                                                         "Entry %s CSN %s greater than snapshot %s\n",
2162                                                         rs->sr_entry->e_name.bv_val,
2163                                                         a->a_nvals[0].bv_val,
2164                                                         ss->ss_ctxcsn[i].bv_val );
2165                                                 return LDAP_SUCCESS;
2166                                         }
2167                                 }
2168                         }
2169
2170                         /* Don't send old entries twice */
2171                         if ( srs->sr_state.ctxcsn ) {
2172                                 for ( i=0; i<srs->sr_state.numcsns; i++ ) {
2173                                         if ( sid == srs->sr_state.sids[i] &&
2174                                                 ber_bvcmp( &a->a_nvals[0],
2175                                                         &srs->sr_state.ctxcsn[i] )<= 0 ) {
2176                                                 Debug( LDAP_DEBUG_SYNC,
2177                                                         "Entry %s CSN %s older or equal to ctx %s\n",
2178                                                         rs->sr_entry->e_name.bv_val,
2179                                                         a->a_nvals[0].bv_val,
2180                                                         srs->sr_state.ctxcsn[i].bv_val );
2181                                                 return LDAP_SUCCESS;
2182                                         }
2183                                 }
2184                         }
2185                 }
2186                 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
2187                         op->o_tmpmemctx );
2188                 rs->sr_ctrls[1] = NULL;
2189                 /* If we're in delta-sync mode, always send a cookie */
2190                 if ( si->si_nopres && si->si_usehint && a ) {
2191                         struct berval cookie;
2192                         slap_compose_sync_cookie( op, &cookie, a->a_nvals, srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
2193                         rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
2194                                 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 1, &cookie );
2195                 } else {
2196                         rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
2197                                 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
2198                 }
2199         } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
2200                 struct berval cookie;
2201
2202                 if ( ss->ss_flags & SS_CHANGED ) {
2203                         slap_compose_sync_cookie( op, &cookie, ss->ss_ctxcsn,
2204                                 srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
2205
2206                         Debug( LDAP_DEBUG_SYNC, "syncprov_search_response: cookie=%s\n", cookie.bv_val, 0, 0 );
2207                 }
2208
2209                 /* Is this a regular refresh?
2210                  * Note: refresh never gets here if there were no changes
2211                  */
2212                 if ( !ss->ss_so ) {
2213                         rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
2214                                 op->o_tmpmemctx );
2215                         rs->sr_ctrls[1] = NULL;
2216                         rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
2217                                 0, 1, &cookie, ( ss->ss_flags & SS_PRESENT ) ?  LDAP_SYNC_REFRESH_PRESENTS :
2218                                         LDAP_SYNC_REFRESH_DELETES );
2219                         op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
2220                 } else {
2221                 /* It's RefreshAndPersist, transition to Persist phase */
2222                         syncprov_sendinfo( op, rs, ( ss->ss_flags & SS_PRESENT ) ?
2223                                 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
2224                                 ( ss->ss_flags & SS_CHANGED ) ? &cookie : NULL,
2225                                 1, NULL, 0 );
2226                         if ( ss->ss_flags & SS_CHANGED )
2227                                 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
2228
2229                         /* Detach this Op from frontend control */
2230                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
2231
2232                         /* But not if this connection was closed along the way */
2233                         if ( op->o_abandon ) {
2234                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
2235                                 /* syncprov_ab_cleanup will free this syncop */
2236                                 return SLAPD_ABANDON;
2237
2238                         } else {
2239                                 ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
2240                                 /* Turn off the refreshing flag */
2241                                 ss->ss_so->s_flags ^= PS_IS_REFRESHING;
2242
2243                                 syncprov_detach_op( op, ss->ss_so, on );
2244
2245                                 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
2246
2247                                 /* If there are queued responses, fire them off */
2248                                 if ( ss->ss_so->s_res )
2249                                         syncprov_qstart( ss->ss_so );
2250                                 ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
2251                         }
2252
2253                         return LDAP_SUCCESS;
2254                 }
2255         }
2256
2257         return SLAP_CB_CONTINUE;
2258 }
2259
2260 static int
2261 syncprov_op_search( Operation *op, SlapReply *rs )
2262 {
2263         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
2264         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2265         slap_callback   *cb;
2266         int gotstate = 0, changed = 0, do_present = 0;
2267         syncops *sop = NULL;
2268         searchstate *ss;
2269         sync_control *srs;
2270         BerVarray ctxcsn;
2271         int i, *sids, numcsns;
2272         struct berval mincsn;
2273
2274         if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
2275
2276         if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
2277                 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
2278                 return rs->sr_err;
2279         }
2280
2281         srs = op->o_controls[slap_cids.sc_LDAPsync];
2282
2283         /* If this is a persistent search, set it up right away */
2284         if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
2285                 syncops so = {0};
2286                 fbase_cookie fc;
2287                 opcookie opc;
2288                 slap_callback sc;
2289
2290                 fc.fss = &so;
2291                 fc.fbase = 0;
2292                 so.s_eid = NOID;
2293                 so.s_op = op;
2294                 so.s_flags = PS_IS_REFRESHING | PS_FIND_BASE;
2295                 /* syncprov_findbase expects to be called as a callback... */
2296                 sc.sc_private = &opc;
2297                 opc.son = on;
2298                 ldap_pvt_thread_mutex_init( &so.s_mutex );
2299                 cb = op->o_callback;
2300                 op->o_callback = &sc;
2301                 rs->sr_err = syncprov_findbase( op, &fc );
2302                 op->o_callback = cb;
2303                 ldap_pvt_thread_mutex_destroy( &so.s_mutex );
2304
2305                 if ( rs->sr_err != LDAP_SUCCESS ) {
2306                         send_ldap_result( op, rs );
2307                         return rs->sr_err;
2308                 }
2309                 sop = ch_malloc( sizeof( syncops ));
2310                 *sop = so;
2311                 ldap_pvt_thread_mutex_init( &sop->s_mutex );
2312                 sop->s_rid = srs->sr_state.rid;
2313                 sop->s_sid = srs->sr_state.sid;
2314                 sop->s_inuse = 1;
2315
2316                 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
2317                 sop->s_next = si->si_ops;
2318                 si->si_ops = sop;
2319                 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
2320         }
2321
2322         /* snapshot the ctxcsn */
2323         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2324         numcsns = si->si_numcsns;
2325         if ( numcsns ) {
2326                 ber_bvarray_dup_x( &ctxcsn, si->si_ctxcsn, op->o_tmpmemctx );
2327                 sids = op->o_tmpalloc( numcsns * sizeof(int), op->o_tmpmemctx );
2328                 for ( i=0; i<numcsns; i++ )
2329                         sids[i] = si->si_sids[i];
2330         } else {
2331                 ctxcsn = NULL;
2332                 sids = NULL;
2333         }
2334         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2335         
2336         /* If we have a cookie, handle the PRESENT lookups */
2337         if ( srs->sr_state.ctxcsn ) {
2338                 sessionlog *sl;
2339                 int i, j;
2340
2341                 /* If we don't have any CSN of our own yet, pretend nothing
2342                  * has changed.
2343                  */
2344                 if ( !numcsns )
2345                         goto no_change;
2346
2347                 if ( !si->si_nopres )
2348                         do_present = SS_PRESENT;
2349
2350                 /* If there are SIDs we don't recognize in the cookie, drop them */
2351                 for (i=0; i<srs->sr_state.numcsns; ) {
2352                         for (j=0; j<numcsns; j++) {
2353                                 if ( srs->sr_state.sids[i] == sids[j] ) {
2354                                         break;
2355                                 }
2356                         }
2357                         /* not found */
2358                         if ( j == numcsns ) {
2359                                 struct berval tmp = srs->sr_state.ctxcsn[i];
2360                                 j = srs->sr_state.numcsns - 1;
2361                                 srs->sr_state.ctxcsn[i] = srs->sr_state.ctxcsn[j];
2362                                 tmp.bv_len = 0;
2363                                 srs->sr_state.ctxcsn[j] = tmp;
2364                                 srs->sr_state.numcsns = j;
2365                                 srs->sr_state.sids[i] = srs->sr_state.sids[j];
2366                                 continue;
2367                         }
2368                         i++;
2369                 }
2370
2371                 /* Find the smallest CSN */
2372                 mincsn = srs->sr_state.ctxcsn[0];
2373                 for ( i=1; i<srs->sr_state.numcsns; i++ ) {
2374                         if ( ber_bvcmp( &mincsn, &srs->sr_state.ctxcsn[i] ) > 0 )
2375                                 mincsn = srs->sr_state.ctxcsn[i];
2376                 }
2377
2378                 /* If nothing has changed, shortcut it */
2379                 if ( srs->sr_state.numcsns == numcsns ) {
2380                         int i, j;
2381                         for ( i=0; i<srs->sr_state.numcsns; i++ ) {
2382                                 for ( j=0; j<numcsns; j++ ) {
2383                                         if ( srs->sr_state.sids[i] != sids[j] )
2384                                                 continue;
2385                                         if ( !bvmatch( &srs->sr_state.ctxcsn[i], &ctxcsn[j] ))
2386                                                 changed = SS_CHANGED;
2387                                         break;
2388                                 }
2389                                 if ( changed )
2390                                         break;
2391                         }
2392                         if ( !changed ) {
2393                                 do_present = 0;
2394 no_change:              if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
2395                                         LDAPControl     *ctrls[2];
2396
2397                                         ctrls[0] = NULL;
2398                                         ctrls[1] = NULL;
2399                                         syncprov_done_ctrl( op, rs, ctrls, 0, 0,
2400                                                 NULL, LDAP_SYNC_REFRESH_DELETES );
2401                                         rs->sr_ctrls = ctrls;
2402                                         rs->sr_err = LDAP_SUCCESS;
2403                                         send_ldap_result( op, rs );
2404                                         rs->sr_ctrls = NULL;
2405                                         return rs->sr_err;
2406                                 }
2407                                 goto shortcut;
2408                         }
2409                 } else {
2410                         /* consumer doesn't have the right number of CSNs */
2411                         changed = SS_CHANGED;
2412                 }
2413                 /* Do we have a sessionlog for this search? */
2414                 sl=si->si_logs;
2415                 if ( sl ) {
2416                         ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
2417                         /* Are there any log entries, and is the consumer state
2418                          * present in the session log?
2419                          */
2420                         if ( sl->sl_num > 0 && ber_bvcmp( &mincsn, &sl->sl_mincsn ) >= 0 ) {
2421                                 do_present = 0;
2422                                 /* mutex is unlocked in playlog */
2423                                 syncprov_playlog( op, rs, sl, srs, ctxcsn, numcsns, sids );
2424                         } else {
2425                                 ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
2426                         }
2427                 }
2428                 /* Is the CSN still present in the database? */
2429                 if ( syncprov_findcsn( op, FIND_CSN ) != LDAP_SUCCESS ) {
2430                         /* No, so a reload is required */
2431                         /* the 2.2 consumer doesn't send this hint */
2432                         if ( si->si_usehint && srs->sr_rhint == 0 ) {
2433                                 if ( ctxcsn )
2434                                         ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
2435                                 if ( sids )
2436                                         op->o_tmpfree( sids, op->o_tmpmemctx );
2437                                 send_ldap_error( op, rs, LDAP_SYNC_REFRESH_REQUIRED, "sync cookie is stale" );
2438                                 return rs->sr_err;
2439                         }
2440                         if ( srs->sr_state.ctxcsn ) {
2441                                 ber_bvarray_free_x( srs->sr_state.ctxcsn, op->o_tmpmemctx );
2442                                 srs->sr_state.ctxcsn = NULL;
2443                         }
2444                         if ( srs->sr_state.sids ) {
2445                                 slap_sl_free( srs->sr_state.sids, op->o_tmpmemctx );
2446                                 srs->sr_state.sids = NULL;
2447                         }
2448                         srs->sr_state.numcsns = 0;
2449                 } else {
2450                         gotstate = 1;
2451                         /* If changed and doing Present lookup, send Present UUIDs */
2452                         if ( do_present && syncprov_findcsn( op, FIND_PRESENT ) !=
2453                                 LDAP_SUCCESS ) {
2454                                 if ( ctxcsn )
2455                                         ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
2456                                 if ( sids )
2457                                         op->o_tmpfree( sids, op->o_tmpmemctx );
2458                                 send_ldap_result( op, rs );
2459                                 return rs->sr_err;
2460                         }
2461                 }
2462         } else {
2463                 /* No consumer state, assume something has changed */
2464                 changed = SS_CHANGED;
2465         }
2466
2467 shortcut:
2468         /* Append CSN range to search filter, save original filter
2469          * for persistent search evaluation
2470          */
2471         if ( sop ) {
2472                 sop->s_filterstr= op->ors_filterstr;
2473         }
2474
2475         /* If something changed, find the changes */
2476         if ( gotstate && changed ) {
2477                 Filter *fand, *fava;
2478
2479                 fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
2480                 fand->f_choice = LDAP_FILTER_AND;
2481                 fand->f_next = NULL;
2482                 fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
2483                 fand->f_and = fava;
2484                 fava->f_choice = LDAP_FILTER_GE;
2485                 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
2486                 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
2487 #ifdef LDAP_COMP_MATCH
2488                 fava->f_ava->aa_cf = NULL;
2489 #endif
2490                 ber_dupbv_x( &fava->f_ava->aa_value, &mincsn, op->o_tmpmemctx );
2491                 fava->f_next = op->ors_filter;
2492                 op->ors_filter = fand;
2493                 filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2494                 if ( sop )
2495                         sop->s_flags |= PS_FIX_FILTER;
2496         }
2497
2498         /* Let our callback add needed info to returned entries */
2499         cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
2500         ss = (searchstate *)(cb+1);
2501         ss->ss_on = on;
2502         ss->ss_so = sop;
2503         ss->ss_flags = do_present | changed;
2504         ss->ss_ctxcsn = ctxcsn;
2505         ss->ss_numcsns = numcsns;
2506         ss->ss_sids = sids;
2507         cb->sc_response = syncprov_search_response;
2508         cb->sc_cleanup = syncprov_search_cleanup;
2509         cb->sc_private = ss;
2510         cb->sc_next = op->o_callback;
2511         op->o_callback = cb;
2512
2513         /* If this is a persistent search and no changes were reported during
2514          * the refresh phase, just invoke the response callback to transition
2515          * us into persist phase
2516          */
2517         if ( !changed ) {
2518                 rs->sr_err = LDAP_SUCCESS;
2519                 rs->sr_nentries = 0;
2520                 send_ldap_result( op, rs );
2521                 return rs->sr_err;
2522         }
2523         return SLAP_CB_CONTINUE;
2524 }
2525
2526 static int
2527 syncprov_operational(
2528         Operation *op,
2529         SlapReply *rs )
2530 {
2531         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
2532         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2533
2534         /* This prevents generating unnecessarily; frontend will strip
2535          * any statically stored copy.
2536          */
2537         if ( op->o_sync != SLAP_CONTROL_NONE )
2538                 return SLAP_CB_CONTINUE;
2539
2540         if ( rs->sr_entry &&
2541                 dn_match( &rs->sr_entry->e_nname, op->o_bd->be_nsuffix )) {
2542
2543                 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
2544                         ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
2545                         Attribute *a, **ap = NULL;
2546
2547                         for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
2548                                 if ( a->a_desc == slap_schema.si_ad_contextCSN )
2549                                         break;
2550                         }
2551
2552                         ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2553                         if ( si->si_ctxcsn ) {
2554                                 if ( !a ) {
2555                                         for ( ap = &rs->sr_operational_attrs; *ap;
2556                                                 ap=&(*ap)->a_next );
2557
2558                                         a = attr_alloc( slap_schema.si_ad_contextCSN );
2559                                         *ap = a;
2560                                 }
2561
2562                                 if ( !ap ) {
2563                                         if ( !(rs->sr_flags & REP_ENTRY_MODIFIABLE) ) {
2564                                                 Entry *e = entry_dup( rs->sr_entry );
2565                                                 if ( rs->sr_flags & REP_ENTRY_MUSTRELEASE ) {
2566                                                         overlay_entry_release_ov( op, rs->sr_entry, 0, on );
2567                                                         rs->sr_flags ^= REP_ENTRY_MUSTRELEASE;
2568                                                 } else if ( rs->sr_flags & REP_ENTRY_MUSTBEFREED ) {
2569                                                         entry_free( rs->sr_entry );
2570                                                 }
2571                                                 rs->sr_entry = e;
2572                                                 rs->sr_flags |=
2573                                                         REP_ENTRY_MODIFIABLE|REP_ENTRY_MUSTBEFREED;
2574                                                 a = attr_find( rs->sr_entry->e_attrs,
2575                                                         slap_schema.si_ad_contextCSN );
2576                                         }
2577                                         if ( a->a_nvals != a->a_vals ) {
2578                                                 ber_bvarray_free( a->a_nvals );
2579                                         }
2580                                         a->a_nvals = NULL;
2581                                         ber_bvarray_free( a->a_vals );
2582                                         a->a_vals = NULL;
2583                                         a->a_numvals = 0;
2584                                 }
2585                                 attr_valadd( a, si->si_ctxcsn, si->si_ctxcsn, si->si_numcsns );
2586                         }
2587                         ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2588                 }
2589         }
2590         return SLAP_CB_CONTINUE;
2591 }
2592
2593 enum {
2594         SP_CHKPT = 1,
2595         SP_SESSL,
2596         SP_NOPRES,
2597         SP_USEHINT
2598 };
2599
2600 static ConfigDriver sp_cf_gen;
2601
2602 static ConfigTable spcfg[] = {
2603         { "syncprov-checkpoint", "ops> <minutes", 3, 3, 0, ARG_MAGIC|SP_CHKPT,
2604                 sp_cf_gen, "( OLcfgOvAt:1.1 NAME 'olcSpCheckpoint' "
2605                         "DESC 'ContextCSN checkpoint interval in ops and minutes' "
2606                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
2607         { "syncprov-sessionlog", "ops", 2, 2, 0, ARG_INT|ARG_MAGIC|SP_SESSL,
2608                 sp_cf_gen, "( OLcfgOvAt:1.2 NAME 'olcSpSessionlog' "
2609                         "DESC 'Session log size in ops' "
2610                         "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
2611         { "syncprov-nopresent", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_NOPRES,
2612                 sp_cf_gen, "( OLcfgOvAt:1.3 NAME 'olcSpNoPresent' "
2613                         "DESC 'Omit Present phase processing' "
2614                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
2615         { "syncprov-reloadhint", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_USEHINT,
2616                 sp_cf_gen, "( OLcfgOvAt:1.4 NAME 'olcSpReloadHint' "
2617                         "DESC 'Observe Reload Hint in Request control' "
2618                         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
2619         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
2620 };
2621
2622 static ConfigOCs spocs[] = {
2623         { "( OLcfgOvOc:1.1 "
2624                 "NAME 'olcSyncProvConfig' "
2625                 "DESC 'SyncRepl Provider configuration' "
2626                 "SUP olcOverlayConfig "
2627                 "MAY ( olcSpCheckpoint "
2628                         "$ olcSpSessionlog "
2629                         "$ olcSpNoPresent "
2630                         "$ olcSpReloadHint "
2631                 ") )",
2632                         Cft_Overlay, spcfg },
2633         { NULL, 0, NULL }
2634 };
2635
2636 static int
2637 sp_cf_gen(ConfigArgs *c)
2638 {
2639         slap_overinst           *on = (slap_overinst *)c->bi;
2640         syncprov_info_t         *si = (syncprov_info_t *)on->on_bi.bi_private;
2641         int rc = 0;
2642
2643         if ( c->op == SLAP_CONFIG_EMIT ) {
2644                 switch ( c->type ) {
2645                 case SP_CHKPT:
2646                         if ( si->si_chkops || si->si_chktime ) {
2647                                 struct berval bv;
2648                                 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
2649                                         "%d %d", si->si_chkops, si->si_chktime );
2650                                 if ( bv.bv_len >= sizeof( c->cr_msg ) ) {
2651                                         rc = 1;
2652                                 } else {
2653                                         bv.bv_val = c->cr_msg;
2654                                         value_add_one( &c->rvalue_vals, &bv );
2655                                 }
2656                         } else {
2657                                 rc = 1;
2658                         }
2659                         break;
2660                 case SP_SESSL:
2661                         if ( si->si_logs ) {
2662                                 c->value_int = si->si_logs->sl_size;
2663                         } else {
2664                                 rc = 1;
2665                         }
2666                         break;
2667                 case SP_NOPRES:
2668                         if ( si->si_nopres ) {
2669                                 c->value_int = 1;
2670                         } else {
2671                                 rc = 1;
2672                         }
2673                         break;
2674                 case SP_USEHINT:
2675                         if ( si->si_usehint ) {
2676                                 c->value_int = 1;
2677                         } else {
2678                                 rc = 1;
2679                         }
2680                         break;
2681                 }
2682                 return rc;
2683         } else if ( c->op == LDAP_MOD_DELETE ) {
2684                 switch ( c->type ) {
2685                 case SP_CHKPT:
2686                         si->si_chkops = 0;
2687                         si->si_chktime = 0;
2688                         break;
2689                 case SP_SESSL:
2690                         if ( si->si_logs )
2691                                 si->si_logs->sl_size = 0;
2692                         else
2693                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2694                         break;
2695                 case SP_NOPRES:
2696                         if ( si->si_nopres )
2697                                 si->si_nopres = 0;
2698                         else
2699                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2700                         break;
2701                 case SP_USEHINT:
2702                         if ( si->si_usehint )
2703                                 si->si_usehint = 0;
2704                         else
2705                                 rc = LDAP_NO_SUCH_ATTRIBUTE;
2706                         break;
2707                 }
2708                 return rc;
2709         }
2710         switch ( c->type ) {
2711         case SP_CHKPT:
2712                 if ( lutil_atoi( &si->si_chkops, c->argv[1] ) != 0 ) {
2713                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint ops # \"%s\"",
2714                                 c->argv[0], c->argv[1] );
2715                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2716                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2717                         return ARG_BAD_CONF;
2718                 }
2719                 if ( si->si_chkops <= 0 ) {
2720                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint ops # \"%d\"",
2721                                 c->argv[0], si->si_chkops );
2722                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2723                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2724                         return ARG_BAD_CONF;
2725                 }
2726                 if ( lutil_atoi( &si->si_chktime, c->argv[2] ) != 0 ) {
2727                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint time \"%s\"",
2728                                 c->argv[0], c->argv[1] );
2729                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2730                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2731                         return ARG_BAD_CONF;
2732                 }
2733                 if ( si->si_chktime <= 0 ) {
2734                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint time \"%d\"",
2735                                 c->argv[0], si->si_chkops );
2736                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2737                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2738                         return ARG_BAD_CONF;
2739                 }
2740                 si->si_chktime *= 60;
2741                 break;
2742         case SP_SESSL: {
2743                 sessionlog *sl;
2744                 int size = c->value_int;
2745
2746                 if ( size < 0 ) {
2747                         snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s size %d is negative",
2748                                 c->argv[0], size );
2749                         Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
2750                                 "%s: %s\n", c->log, c->cr_msg, 0 );
2751                         return ARG_BAD_CONF;
2752                 }
2753                 sl = si->si_logs;
2754                 if ( !sl ) {
2755                         sl = ch_malloc( sizeof( sessionlog ) + LDAP_LUTIL_CSNSTR_BUFSIZE );
2756                         sl->sl_mincsn.bv_val = (char *)(sl+1);
2757                         sl->sl_mincsn.bv_len = 0;
2758                         sl->sl_num = 0;
2759                         sl->sl_head = sl->sl_tail = NULL;
2760                         ldap_pvt_thread_mutex_init( &sl->sl_mutex );
2761                         si->si_logs = sl;
2762                 }
2763                 sl->sl_size = size;
2764                 }
2765                 break;
2766         case SP_NOPRES:
2767                 si->si_nopres = c->value_int;
2768                 break;
2769         case SP_USEHINT:
2770                 si->si_usehint = c->value_int;
2771                 break;
2772         }
2773         return rc;
2774 }
2775
2776 /* ITS#3456 we cannot run this search on the main thread, must use a
2777  * child thread in order to insure we have a big enough stack.
2778  */
2779 static void *
2780 syncprov_db_otask(
2781         void *ptr
2782 )
2783 {
2784         syncprov_findcsn( ptr, FIND_MAXCSN );
2785         return NULL;
2786 }
2787
2788 /* Read any existing contextCSN from the underlying db.
2789  * Then search for any entries newer than that. If no value exists,
2790  * just generate it. Cache whatever result.
2791  */
2792 static int
2793 syncprov_db_open(
2794         BackendDB *be,
2795         ConfigReply *cr
2796 )
2797 {
2798         slap_overinst   *on = (slap_overinst *) be->bd_info;
2799         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2800
2801         Connection conn = { 0 };
2802         OperationBuffer opbuf;
2803         Operation *op;
2804         Entry *e = NULL;
2805         Attribute *a;
2806         int rc;
2807         void *thrctx = NULL;
2808
2809         if ( !SLAP_LASTMOD( be )) {
2810                 Debug( LDAP_DEBUG_ANY,
2811                         "syncprov_db_open: invalid config, lastmod must be enabled\n", 0, 0, 0 );
2812                 return -1;
2813         }
2814
2815         if ( slapMode & SLAP_TOOL_MODE ) {
2816                 return 0;
2817         }
2818
2819         rc = overlay_register_control( be, LDAP_CONTROL_SYNC );
2820         if ( rc ) {
2821                 return rc;
2822         }
2823
2824         thrctx = ldap_pvt_thread_pool_context();
2825         connection_fake_init( &conn, &opbuf, thrctx );
2826         op = &opbuf.ob_op;
2827         op->o_bd = be;
2828         op->o_dn = be->be_rootdn;
2829         op->o_ndn = be->be_rootndn;
2830
2831         rc = overlay_entry_get_ov( op, be->be_nsuffix, NULL,
2832                 slap_schema.si_ad_contextCSN, 0, &e, on );
2833
2834         if ( e ) {
2835                 ldap_pvt_thread_t tid;
2836
2837                 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
2838                 if ( a ) {
2839                         ber_bvarray_dup_x( &si->si_ctxcsn, a->a_vals, NULL );
2840                         si->si_numcsns = a->a_numvals;
2841                         si->si_sids = slap_parse_csn_sids( si->si_ctxcsn, a->a_numvals, NULL );
2842                 }
2843                 overlay_entry_release_ov( op, e, 0, on );
2844                 if ( si->si_ctxcsn && !SLAP_DBCLEAN( be )) {
2845                         op->o_req_dn = be->be_suffix[0];
2846                         op->o_req_ndn = be->be_nsuffix[0];
2847                         op->ors_scope = LDAP_SCOPE_SUBTREE;
2848                         ldap_pvt_thread_create( &tid, 0, syncprov_db_otask, op );
2849                         ldap_pvt_thread_join( tid, NULL );
2850                 }
2851         }
2852
2853         /* Didn't find a contextCSN, should we generate one? */
2854         if ( !si->si_ctxcsn ) {
2855                 char csnbuf[ LDAP_LUTIL_CSNSTR_BUFSIZE ];
2856                 struct berval csn;
2857
2858                 if ( SLAP_SYNC_SHADOW( op->o_bd )) {
2859                 /* If we're also a consumer, then don't generate anything.
2860                  * Wait for our provider to send it to us, or for a local
2861                  * modify if we have multimaster.
2862                  */
2863                         goto out;
2864                 }
2865                 csn.bv_val = csnbuf;
2866                 csn.bv_len = sizeof( csnbuf );
2867                 slap_get_csn( op, &csn, 0 );
2868                 value_add_one( &si->si_ctxcsn, &csn );
2869                 si->si_numcsns = 1;
2870                 si->si_sids = ch_malloc( sizeof(int) );
2871                 si->si_sids[0] = slap_serverID;
2872
2873                 /* make sure we do a checkpoint on close */
2874                 si->si_numops++;
2875         }
2876
2877 out:
2878         op->o_bd->bd_info = (BackendInfo *)on;
2879         return 0;
2880 }
2881
2882 /* Write the current contextCSN into the underlying db.
2883  */
2884 static int
2885 syncprov_db_close(
2886         BackendDB *be,
2887         ConfigReply *cr
2888 )
2889 {
2890     slap_overinst   *on = (slap_overinst *) be->bd_info;
2891     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2892
2893         if ( slapMode & SLAP_TOOL_MODE ) {
2894                 return 0;
2895         }
2896         if ( si->si_numops ) {
2897                 Connection conn = {0};
2898                 OperationBuffer opbuf;
2899                 Operation *op;
2900                 SlapReply rs = {REP_RESULT};
2901                 void *thrctx;
2902
2903                 thrctx = ldap_pvt_thread_pool_context();
2904                 connection_fake_init( &conn, &opbuf, thrctx );
2905                 op = &opbuf.ob_op;
2906                 op->o_bd = be;
2907                 op->o_dn = be->be_rootdn;
2908                 op->o_ndn = be->be_rootndn;
2909                 syncprov_checkpoint( op, &rs, on );
2910         }
2911
2912     return 0;
2913 }
2914
2915 static int
2916 syncprov_db_init(
2917         BackendDB *be,
2918         ConfigReply *cr
2919 )
2920 {
2921         slap_overinst   *on = (slap_overinst *)be->bd_info;
2922         syncprov_info_t *si;
2923
2924         if ( SLAP_ISGLOBALOVERLAY( be ) ) {
2925                 Debug( LDAP_DEBUG_ANY,
2926                         "syncprov must be instantiated within a database.\n",
2927                         0, 0, 0 );
2928                 return 1;
2929         }
2930
2931         si = ch_calloc(1, sizeof(syncprov_info_t));
2932         on->on_bi.bi_private = si;
2933         ldap_pvt_thread_rdwr_init( &si->si_csn_rwlock );
2934         ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
2935         ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
2936
2937         csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
2938         csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
2939         csn_anlist[1].an_desc = slap_schema.si_ad_entryUUID;
2940         csn_anlist[1].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2941
2942         uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
2943         uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2944
2945         return 0;
2946 }
2947
2948 static int
2949 syncprov_db_destroy(
2950         BackendDB *be,
2951         ConfigReply *cr
2952 )
2953 {
2954         slap_overinst   *on = (slap_overinst *)be->bd_info;
2955         syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2956
2957         if ( si ) {
2958                 if ( si->si_logs ) {
2959                         slog_entry *se = si->si_logs->sl_head;
2960
2961                         while ( se ) {
2962                                 slog_entry *se_next = se->se_next;
2963                                 ch_free( se );
2964                                 se = se_next;
2965                         }
2966                                 
2967                         ch_free( si->si_logs );
2968                 }
2969                 if ( si->si_ctxcsn )
2970                         ber_bvarray_free( si->si_ctxcsn );
2971                 if ( si->si_sids )
2972                         ch_free( si->si_sids );
2973                 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
2974                 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
2975                 ldap_pvt_thread_rdwr_destroy( &si->si_csn_rwlock );
2976                 ch_free( si );
2977         }
2978
2979         return 0;
2980 }
2981
2982 static int syncprov_parseCtrl (
2983         Operation *op,
2984         SlapReply *rs,
2985         LDAPControl *ctrl )
2986 {
2987         ber_tag_t tag;
2988         BerElementBuffer berbuf;
2989         BerElement *ber = (BerElement *)&berbuf;
2990         ber_int_t mode;
2991         ber_len_t len;
2992         struct berval cookie = BER_BVNULL;
2993         sync_control *sr;
2994         int rhint = 0;
2995
2996         if ( op->o_sync != SLAP_CONTROL_NONE ) {
2997                 rs->sr_text = "Sync control specified multiple times";
2998                 return LDAP_PROTOCOL_ERROR;
2999         }
3000
3001         if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
3002                 rs->sr_text = "Sync control specified with pagedResults control";
3003                 return LDAP_PROTOCOL_ERROR;
3004         }
3005
3006         if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
3007                 rs->sr_text = "Sync control value is absent";
3008                 return LDAP_PROTOCOL_ERROR;
3009         }
3010
3011         if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
3012                 rs->sr_text = "Sync control value is empty";
3013                 return LDAP_PROTOCOL_ERROR;
3014         }
3015
3016         /* Parse the control value
3017          *      syncRequestValue ::= SEQUENCE {
3018          *              mode   ENUMERATED {
3019          *                      -- 0 unused
3020          *                      refreshOnly             (1),
3021          *                      -- 2 reserved
3022          *                      refreshAndPersist       (3)
3023          *              },
3024          *              cookie  syncCookie OPTIONAL
3025          *      }
3026          */
3027
3028         ber_init2( ber, &ctrl->ldctl_value, 0 );
3029
3030         if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
3031                 rs->sr_text = "Sync control : mode decoding error";
3032                 return LDAP_PROTOCOL_ERROR;
3033         }
3034
3035         switch( mode ) {
3036         case LDAP_SYNC_REFRESH_ONLY:
3037                 mode = SLAP_SYNC_REFRESH;
3038                 break;
3039         case LDAP_SYNC_REFRESH_AND_PERSIST:
3040                 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
3041                 break;
3042         default:
3043                 rs->sr_text = "Sync control : unknown update mode";
3044                 return LDAP_PROTOCOL_ERROR;
3045         }
3046
3047         tag = ber_peek_tag( ber, &len );
3048
3049         if ( tag == LDAP_TAG_SYNC_COOKIE ) {
3050                 if (( ber_scanf( ber, /*{*/ "m", &cookie )) == LBER_ERROR ) {
3051                         rs->sr_text = "Sync control : cookie decoding error";
3052                         return LDAP_PROTOCOL_ERROR;
3053                 }
3054                 tag = ber_peek_tag( ber, &len );
3055         }
3056         if ( tag == LDAP_TAG_RELOAD_HINT ) {
3057                 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
3058                         rs->sr_text = "Sync control : rhint decoding error";
3059                         return LDAP_PROTOCOL_ERROR;
3060                 }
3061         }
3062         if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
3063                         rs->sr_text = "Sync control : decoding error";
3064                         return LDAP_PROTOCOL_ERROR;
3065         }
3066         sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
3067         sr->sr_rhint = rhint;
3068         if (!BER_BVISNULL(&cookie)) {
3069                 ber_dupbv_x( &sr->sr_state.octet_str, &cookie, op->o_tmpmemctx );
3070                 /* If parse fails, pretend no cookie was sent */
3071                 if ( slap_parse_sync_cookie( &sr->sr_state, op->o_tmpmemctx ) ||
3072                         sr->sr_state.rid == -1 ) {
3073                         if ( sr->sr_state.ctxcsn ) {
3074                                 ber_bvarray_free_x( sr->sr_state.ctxcsn, op->o_tmpmemctx );
3075                                 sr->sr_state.ctxcsn = NULL;
3076                         }
3077                         sr->sr_state.numcsns = 0;
3078                 }
3079         }
3080
3081         op->o_controls[slap_cids.sc_LDAPsync] = sr;
3082
3083         op->o_sync = ctrl->ldctl_iscritical
3084                 ? SLAP_CONTROL_CRITICAL
3085                 : SLAP_CONTROL_NONCRITICAL;
3086
3087         op->o_sync_mode |= mode;        /* o_sync_mode shares o_sync */
3088
3089         return LDAP_SUCCESS;
3090 }
3091
3092 /* This overlay is set up for dynamic loading via moduleload. For static
3093  * configuration, you'll need to arrange for the slap_overinst to be
3094  * initialized and registered by some other function inside slapd.
3095  */
3096
3097 static slap_overinst            syncprov;
3098
3099 int
3100 syncprov_initialize()
3101 {
3102         int rc;
3103
3104         rc = register_supported_control( LDAP_CONTROL_SYNC,
3105                 SLAP_CTRL_SEARCH, NULL,
3106                 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
3107         if ( rc != LDAP_SUCCESS ) {
3108                 Debug( LDAP_DEBUG_ANY,
3109                         "syncprov_init: Failed to register control %d\n", rc, 0, 0 );
3110                 return rc;
3111         }
3112
3113         syncprov.on_bi.bi_type = "syncprov";
3114         syncprov.on_bi.bi_db_init = syncprov_db_init;
3115         syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
3116         syncprov.on_bi.bi_db_open = syncprov_db_open;
3117         syncprov.on_bi.bi_db_close = syncprov_db_close;
3118
3119         syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
3120         syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
3121
3122         syncprov.on_bi.bi_op_add = syncprov_op_mod;
3123         syncprov.on_bi.bi_op_compare = syncprov_op_compare;
3124         syncprov.on_bi.bi_op_delete = syncprov_op_mod;
3125         syncprov.on_bi.bi_op_modify = syncprov_op_mod;
3126         syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
3127         syncprov.on_bi.bi_op_search = syncprov_op_search;
3128         syncprov.on_bi.bi_extended = syncprov_op_extended;
3129         syncprov.on_bi.bi_operational = syncprov_operational;
3130
3131         syncprov.on_bi.bi_cf_ocs = spocs;
3132
3133         generic_filter.f_desc = slap_schema.si_ad_objectClass;
3134
3135         rc = config_register_schema( spcfg, spocs );
3136         if ( rc ) return rc;
3137
3138         return overlay_register( &syncprov );
3139 }
3140
3141 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
3142 int
3143 init_module( int argc, char *argv[] )
3144 {
3145         return syncprov_initialize();
3146 }
3147 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
3148
3149 #endif /* defined(SLAPD_OVER_SYNCPROV) */