Debian Codegraph @

servers/slapd/overlays/syncprov.c

raw
1 /* $OpenLDAP$ */
2 /* syncprov.c - syncrepl provider */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 *
5 * Copyright 2004-2024 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 "slap-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 struct berval mt_dn;
45 ldap_pvt_thread_mutex_t mt_mutex;
46 } modtarget;
47
48 /* All the info of a psearch result that's shared between
49 * multiple queues
50 */
51 typedef struct resinfo {
52 struct syncres *ri_list;
53 Entry *ri_e;
54 struct berval ri_dn;
55 struct berval ri_ndn;
56 struct berval ri_uuid;
57 struct berval ri_csn;
58 struct berval ri_cookie;
59 char ri_isref;
60 ldap_pvt_thread_mutex_t ri_mutex;
61 } resinfo;
62
63 /* A queued result of a persistent search */
64 typedef struct syncres {
65 struct syncres *s_next; /* list of results on this psearch queue */
66 struct syncres *s_rilist; /* list of psearches using this result */
67 resinfo *s_info;
68 char s_mode;
69 } syncres;
70
71 /* Record of a persistent search */
72 typedef struct syncops {
73 struct syncops *s_next;
74 struct syncprov_info_t *s_si;
75 struct berval s_base; /* ndn of search base */
76 ID s_eid; /* entryID of search base */
77 Operation *s_op; /* search op */
78 int s_rid;
79 int s_sid;
80 struct berval s_filterstr;
81 int s_flags; /* search status */
82 #define PS_IS_REFRESHING 0x01
83 #define PS_IS_DETACHED 0x02
84 #define PS_WROTE_BASE 0x04
85 #define PS_FIND_BASE 0x08
86 #define PS_FIX_FILTER 0x10
87 #define PS_TASK_QUEUED 0x20
88
89 int s_inuse; /* reference count */
90 struct syncres *s_res;
91 struct syncres *s_restail;
92 void *s_pool_cookie;
93 ldap_pvt_thread_mutex_t s_mutex;
94 } syncops;
95
96 /* A received sync control */
97 typedef struct sync_control {
98 struct sync_cookie sr_state;
99 int sr_rhint;
100 } sync_control;
101
102 #if 0 /* moved back to slap.h */
103 #define o_sync o_ctrlflag[slap_cids.sc_LDAPsync]
104 #endif
105 /* o_sync_mode uses data bits of o_sync */
106 #define o_sync_mode o_ctrlflag[slap_cids.sc_LDAPsync]
107
108 #define SLAP_SYNC_NONE (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
109 #define SLAP_SYNC_REFRESH (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
110 #define SLAP_SYNC_PERSIST (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
111 #define SLAP_SYNC_REFRESH_AND_PERSIST (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
112
113 /* Record of which searches matched at premodify step */
114 typedef struct syncmatches {
115 struct syncmatches *sm_next;
116 syncops *sm_op;
117 } syncmatches;
118
119 /* Session log data */
120 typedef struct slog_entry {
121 struct berval se_uuid;
122 struct berval se_csn;
123 int se_sid;
124 ber_tag_t se_tag;
125 } slog_entry;
126
127 typedef struct sessionlog {
128 BerVarray sl_mincsn;
129 int *sl_sids;
130 int sl_numcsns;
131 int sl_num;
132 int sl_size;
133 int sl_playing;
134 TAvlnode *sl_entries;
135 ldap_pvt_thread_rdwr_t sl_mutex;
136 } sessionlog;
137
138 /* Accesslog callback data */
139 typedef struct syncprov_accesslog_deletes {
140 Operation *op;
141 SlapReply *rs;
142 sync_control *srs;
143 BerVarray ctxcsn;
144 int numcsns, *sids;
145 Avlnode *uuids;
146 BerVarray uuid_list;
147 int ndel, list_len;
148 char *uuid_buf;
149 } syncprov_accesslog_deletes;
150
151 /* The main state for this overlay */
152 typedef struct syncprov_info_t {
153 syncops *si_ops;
154 struct berval si_contextdn;
155 struct berval si_logbase;
156 BerVarray si_ctxcsn; /* ldapsync context */
157 int *si_sids;
158 int si_numcsns;
159 int si_chkops; /* checkpointing info */
160 int si_chktime;
161 int si_numops; /* number of ops since last checkpoint */
162 int si_nopres; /* Skip present phase */
163 int si_usehint; /* use reload hint */
164 int si_active; /* True if there are active mods */
165 int si_dirty; /* True if the context is dirty, i.e changes
166 * have been made without updating the csn. */
167 time_t si_chklast; /* time of last checkpoint */
168 Avlnode *si_mods; /* entries being modified */
169 sessionlog *si_logs;
170 ldap_pvt_thread_rdwr_t si_csn_rwlock;
171 ldap_pvt_thread_mutex_t si_ops_mutex;
172 ldap_pvt_thread_mutex_t si_mods_mutex;
173 ldap_pvt_thread_mutex_t si_resp_mutex;
174 } syncprov_info_t;
175
176 typedef struct opcookie {
177 slap_overinst *son;
178 syncmatches *smatches;
179 modtarget *smt;
180 Entry *se;
181 struct berval sdn; /* DN of entry, for deletes */
182 struct berval sndn;
183 struct berval suuid; /* UUID of entry */
184 struct berval sctxcsn;
185 short osid; /* sid of op csn */
186 short rsid; /* sid of relay */
187 short sreference; /* Is the entry a reference? */
188 syncres ssres;
189 } opcookie;
190
191 typedef struct fbase_cookie {
192 struct berval *fdn; /* DN of a modified entry, for scope testing */
193 syncops *fss; /* persistent search we're testing against */
194 int fbase; /* if TRUE we found the search base and it's still valid */
195 int fscope; /* if TRUE then fdn is within the psearch scope */
196 } fbase_cookie;
197
198 static AttributeName csn_anlist[3];
199 static AttributeName uuid_anlist[2];
200
201 static AttributeDescription *ad_reqType, *ad_reqResult, *ad_reqDN,
202 *ad_reqEntryUUID, *ad_minCSN, *ad_reqNewDN;
203
204 /* Build a LDAPsync intermediate state control */
205 static int
206 syncprov_state_ctrl(
207 Operation *op,
208 SlapReply *rs,
209 Entry *e,
210 int entry_sync_state,
211 LDAPControl **ctrls,
212 int num_ctrls,
213 int send_cookie,
214 struct berval *cookie )
215 {
216 Attribute* a;
217 int ret;
218
219 BerElementBuffer berbuf;
220 BerElement *ber = (BerElement *)&berbuf;
221 LDAPControl *cp;
222 struct berval bv;
223 struct berval entryuuid_bv = BER_BVNULL;
224
225 ber_init2( ber, 0, LBER_USE_DER );
226 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
227
228 for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
229 AttributeDescription *desc = a->a_desc;
230 if ( desc == slap_schema.si_ad_entryUUID ) {
231 entryuuid_bv = a->a_nvals[0];
232 break;
233 }
234 }
235
236 /* FIXME: what if entryuuid is NULL or empty ? */
237
238 if ( send_cookie && cookie ) {
239 ber_printf( ber, "{eOON}",
240 entry_sync_state, &entryuuid_bv, cookie );
241 } else {
242 ber_printf( ber, "{eON}",
243 entry_sync_state, &entryuuid_bv );
244 }
245
246 ret = ber_flatten2( ber, &bv, 0 );
247 if ( ret == 0 ) {
248 cp = op->o_tmpalloc( sizeof( LDAPControl ) + bv.bv_len, op->o_tmpmemctx );
249 cp->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
250 cp->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
251 cp->ldctl_value.bv_val = (char *)&cp[1];
252 cp->ldctl_value.bv_len = bv.bv_len;
253 AC_MEMCPY( cp->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
254 ctrls[num_ctrls] = cp;
255 }
256 ber_free_buf( ber );
257
258 if ( ret < 0 ) {
259 Debug( LDAP_DEBUG_TRACE,
260 "slap_build_sync_ctrl: ber_flatten2 failed (%d)\n",
261 ret );
262 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
263 return LDAP_OTHER;
264 }
265
266 return LDAP_SUCCESS;
267 }
268
269 /* Build a LDAPsync final state control */
270 static int
271 syncprov_done_ctrl(
272 Operation *op,
273 SlapReply *rs,
274 LDAPControl **ctrls,
275 int num_ctrls,
276 int send_cookie,
277 struct berval *cookie,
278 int refreshDeletes )
279 {
280 int ret;
281 BerElementBuffer berbuf;
282 BerElement *ber = (BerElement *)&berbuf;
283 LDAPControl *cp;
284 struct berval bv;
285
286 ber_init2( ber, NULL, LBER_USE_DER );
287 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
288
289 ber_printf( ber, "{" );
290 if ( send_cookie && cookie ) {
291 ber_printf( ber, "O", cookie );
292 }
293 if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
294 ber_printf( ber, "b", refreshDeletes );
295 }
296 ber_printf( ber, "N}" );
297
298 ret = ber_flatten2( ber, &bv, 0 );
299 if ( ret == 0 ) {
300 cp = op->o_tmpalloc( sizeof( LDAPControl ) + bv.bv_len, op->o_tmpmemctx );
301 cp->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
302 cp->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
303 cp->ldctl_value.bv_val = (char *)&cp[1];
304 cp->ldctl_value.bv_len = bv.bv_len;
305 AC_MEMCPY( cp->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
306 ctrls[num_ctrls] = cp;
307 }
308
309 ber_free_buf( ber );
310
311 if ( ret < 0 ) {
312 Debug( LDAP_DEBUG_TRACE,
313 "syncprov_done_ctrl: ber_flatten2 failed (%d)\n",
314 ret );
315 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
316 return LDAP_OTHER;
317 }
318
319 return LDAP_SUCCESS;
320 }
321
322 static int
323 syncprov_sendinfo(
324 Operation *op,
325 SlapReply *rs,
326 int type,
327 struct berval *cookie,
328 int refreshDone,
329 BerVarray syncUUIDs,
330 int refreshDeletes )
331 {
332 BerElementBuffer berbuf;
333 BerElement *ber = (BerElement *)&berbuf;
334 struct berval rspdata;
335
336 int ret;
337
338 ber_init2( ber, NULL, LBER_USE_DER );
339 ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
340
341 if ( type ) {
342 switch ( type ) {
343 case LDAP_TAG_SYNC_NEW_COOKIE:
344 Debug( LDAP_DEBUG_SYNC, "%s syncprov_sendinfo: "
345 "sending a new cookie=%s\n",
346 op->o_log_prefix, cookie->bv_val );
347 ber_printf( ber, "tO", type, cookie );
348 break;
349 case LDAP_TAG_SYNC_REFRESH_DELETE:
350 case LDAP_TAG_SYNC_REFRESH_PRESENT:
351 Debug( LDAP_DEBUG_SYNC, "%s syncprov_sendinfo: "
352 "%s cookie=%s\n",
353 op->o_log_prefix,
354 type == LDAP_TAG_SYNC_REFRESH_DELETE ? "refreshDelete" : "refreshPresent",
355 cookie ? cookie->bv_val : "" );
356 ber_printf( ber, "t{", type );
357 if ( cookie ) {
358 ber_printf( ber, "O", cookie );
359 }
360 if ( refreshDone == 0 ) {
361 ber_printf( ber, "b", refreshDone );
362 }
363 ber_printf( ber, "N}" );
364 break;
365 case LDAP_TAG_SYNC_ID_SET:
366 Debug( LDAP_DEBUG_SYNC, "%s syncprov_sendinfo: "
367 "%s syncIdSet cookie=%s\n",
368 op->o_log_prefix, refreshDeletes ? "delete" : "present",
369 cookie ? cookie->bv_val : "" );
370 ber_printf( ber, "t{", type );
371 if ( cookie ) {
372 ber_printf( ber, "O", cookie );
373 }
374 if ( refreshDeletes == 1 ) {
375 ber_printf( ber, "b", refreshDeletes );
376 }
377 ber_printf( ber, "[W]", syncUUIDs );
378 ber_printf( ber, "N}" );
379 break;
380 default:
381 Debug( LDAP_DEBUG_TRACE,
382 "%s syncprov_sendinfo: invalid syncinfo type (%d)\n",
383 op->o_log_prefix, type );
384 return LDAP_OTHER;
385 }
386 }
387
388 ret = ber_flatten2( ber, &rspdata, 0 );
389
390 if ( ret < 0 ) {
391 Debug( LDAP_DEBUG_TRACE,
392 "syncprov_sendinfo: ber_flatten2 failed (%d)\n",
393 ret );
394 send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
395 return LDAP_OTHER;
396 }
397
398 rs->sr_rspoid = LDAP_SYNC_INFO;
399 rs->sr_rspdata = &rspdata;
400 send_ldap_intermediate( op, rs );
401 rs->sr_rspdata = NULL;
402 ber_free_buf( ber );
403
404 return LDAP_SUCCESS;
405 }
406
407 /* Find a modtarget in an AVL tree */
408 static int
409 sp_avl_cmp( const void *c1, const void *c2 )
410 {
411 const modtarget *m1, *m2;
412 int rc;
413
414 m1 = c1; m2 = c2;
415 rc = m1->mt_dn.bv_len - m2->mt_dn.bv_len;
416
417 if ( rc ) return rc;
418 return ber_bvcmp( &m1->mt_dn, &m2->mt_dn );
419 }
420
421 static int
422 sp_uuid_cmp( const void *l, const void *r )
423 {
424 const struct berval *left = l, *right = r;
425
426 return ber_bvcmp( left, right );
427 }
428
429 static int
430 syncprov_sessionlog_cmp( const void *l, const void *r )
431 {
432 const slog_entry *left = l, *right = r;
433 int ret = ber_bvcmp( &left->se_csn, &right->se_csn );
434 if ( !ret )
435 ret = ber_bvcmp( &left->se_uuid, &right->se_uuid );
436 /* Only time we have two modifications with same CSN is when we detect a
437 * rename during replication.
438 * We invert the test here because LDAP_REQ_MODDN is
439 * numerically greater than LDAP_REQ_MODIFY but we
440 * want it to occur first.
441 */
442 if ( !ret )
443 ret = right->se_tag - left->se_tag;
444
445 return ret;
446 }
447
448 /* syncprov_findbase:
449 * finds the true DN of the base of a search (with alias dereferencing) and
450 * checks to make sure the base entry doesn't get replaced with a different
451 * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
452 * change is detected, any persistent search on this base must be terminated /
453 * reloaded.
454 * On the first call, we just save the DN and entryID. On subsequent calls
455 * we compare the DN and entryID with the saved values.
456 */
457 static int
458 findbase_cb( Operation *op, SlapReply *rs )
459 {
460 slap_callback *sc = op->o_callback;
461
462 if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
463 fbase_cookie *fc = sc->sc_private;
464
465 /* If no entryID, we're looking for the first time.
466 * Just store whatever we got.
467 */
468 if ( fc->fss->s_eid == NOID ) {
469 fc->fbase = 2;
470 fc->fss->s_eid = rs->sr_entry->e_id;
471 ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
472
473 } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
474 dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
475
476 /* OK, the DN is the same and the entryID is the same. */
477 fc->fbase = 1;
478 }
479 }
480 if ( rs->sr_err != LDAP_SUCCESS ) {
481 Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err );
482 }
483 return LDAP_SUCCESS;
484 }
485
486 static Filter generic_filter = { LDAP_FILTER_PRESENT, { 0 }, NULL };
487 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
488
489 static int
490 syncprov_findbase( Operation *op, fbase_cookie *fc )
491 {
492 /* Use basic parameters from syncrepl search, but use
493 * current op's threadctx / tmpmemctx
494 */
495 ldap_pvt_thread_mutex_lock( &fc->fss->s_mutex );
496 if ( fc->fss->s_flags & PS_FIND_BASE ) {
497 slap_callback cb = {0};
498 Operation fop;
499 SlapReply frs = { REP_RESULT };
500 int rc;
501
502 fc->fss->s_flags ^= PS_FIND_BASE;
503 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
504
505 fop = *fc->fss->s_op;
506
507 fop.o_bd = fop.o_bd->bd_self;
508 fop.o_hdr = op->o_hdr;
509 fop.o_time = op->o_time;
510 fop.o_tincr = op->o_tincr;
511 fop.o_extra = op->o_extra;
512
513 cb.sc_response = findbase_cb;
514 cb.sc_private = fc;
515
516 fop.o_sync_mode = 0; /* turn off sync mode */
517 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
518 fop.o_callback = &cb;
519 fop.o_tag = LDAP_REQ_SEARCH;
520 fop.ors_scope = LDAP_SCOPE_BASE;
521 fop.ors_limit = NULL;
522 fop.ors_slimit = 1;
523 fop.ors_tlimit = SLAP_NO_LIMIT;
524 fop.ors_attrs = slap_anlist_no_attrs;
525 fop.ors_attrsonly = 1;
526 fop.ors_filter = &generic_filter;
527 fop.ors_filterstr = generic_filterstr;
528
529 Debug( LDAP_DEBUG_SYNC, "%s syncprov_findbase: searching\n", op->o_log_prefix );
530 rc = fop.o_bd->be_search( &fop, &frs );
531 } else {
532 ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
533 fc->fbase = 1;
534 }
535
536 /* After the first call, see if the fdn resides in the scope */
537 if ( fc->fbase == 1 ) {
538 switch ( fc->fss->s_op->ors_scope ) {
539 case LDAP_SCOPE_BASE:
540 fc->fscope = dn_match( fc->fdn, &fc->fss->s_base );
541 break;
542 case LDAP_SCOPE_ONELEVEL: {
543 struct berval pdn;
544 dnParent( fc->fdn, &pdn );
545 fc->fscope = dn_match( &pdn, &fc->fss->s_base );
546 break; }
547 case LDAP_SCOPE_SUBTREE:
548 fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base );
549 break;
550 case LDAP_SCOPE_SUBORDINATE:
551 fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base ) &&
552 !dn_match( fc->fdn, &fc->fss->s_base );
553 break;
554 }
555 }
556
557 if ( fc->fbase )
558 return LDAP_SUCCESS;
559
560 /* If entryID has changed, then the base of this search has
561 * changed. Invalidate the psearch.
562 */
563 return LDAP_NO_SUCH_OBJECT;
564 }
565
566 /* syncprov_findcsn:
567 * This function has three different purposes, but they all use a search
568 * that filters on entryCSN so they're combined here.
569 * 1: at startup time, after a contextCSN has been read from the database,
570 * we search for all entries with CSN >= contextCSN in case the contextCSN
571 * was not checkpointed at the previous shutdown.
572 *
573 * 2: when the current contextCSN is known and we have a sync cookie, we search
574 * for one entry with CSN = the cookie CSN. If not found, try <= cookie CSN.
575 * If an entry is found, the cookie CSN is valid, otherwise it is stale.
576 *
577 * 3: during a refresh phase, we search for all entries with CSN <= the cookie
578 * CSN, and generate Present records for them. We always collect this result
579 * in SyncID sets, even if there's only one match.
580 */
581 typedef enum find_csn_t {
582 FIND_MAXCSN = 1,
583 FIND_CSN = 2,
584 FIND_PRESENT = 3
585 } find_csn_t;
586
587 static int
588 findmax_cb( Operation *op, SlapReply *rs )
589 {
590 if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
591 struct berval *maxcsn = op->o_callback->sc_private;
592 Attribute *a = attr_find( rs->sr_entry->e_attrs,
593 slap_schema.si_ad_entryCSN );
594
595 if ( a && ber_bvcmp( &a->a_vals[0], maxcsn ) > 0 &&
596 slap_parse_csn_sid( &a->a_vals[0] ) == slap_serverID ) {
597 maxcsn->bv_len = a->a_vals[0].bv_len;
598 strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
599 }
600 }
601 return LDAP_SUCCESS;
602 }
603
604 static int
605 findcsn_cb( Operation *op, SlapReply *rs )
606 {
607 slap_callback *sc = op->o_callback;
608
609 /* We just want to know that at least one exists, so it's OK if
610 * we exceed the unchecked limit.
611 */
612 if ( rs->sr_err == LDAP_ADMINLIMIT_EXCEEDED ||
613 (rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS )) {
614 sc->sc_private = (void *)1;
615 }
616 return LDAP_SUCCESS;
617 }
618
619 /* Build a list of entryUUIDs for sending in a SyncID set */
620
621 #define UUID_LEN 16
622
623 typedef struct fpres_cookie {
624 int num;
625 BerVarray uuids;
626 char *last;
627 } fpres_cookie;
628
629 static int
630 findpres_cb( Operation *op, SlapReply *rs )
631 {
632 slap_callback *sc = op->o_callback;
633 fpres_cookie *pc = sc->sc_private;
634 Attribute *a;
635 int ret = SLAP_CB_CONTINUE;
636
637 switch ( rs->sr_type ) {
638 case REP_SEARCH:
639 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
640 if ( a ) {
641 pc->uuids[pc->num].bv_val = pc->last;
642 AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
643 pc->uuids[pc->num].bv_len );
644 pc->num++;
645 pc->last = pc->uuids[pc->num].bv_val;
646 pc->uuids[pc->num].bv_val = NULL;
647 }
648 ret = LDAP_SUCCESS;
649 if ( pc->num != SLAP_SYNCUUID_SET_SIZE )
650 break;
651 /* FALLTHRU */
652 case REP_RESULT:
653 ret = rs->sr_err;
654 if ( pc->num ) {
655 ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
656 0, pc->uuids, 0 );
657 pc->uuids[pc->num].bv_val = pc->last;
658 pc->num = 0;
659 pc->last = pc->uuids[0].bv_val;
660 }
661 break;
662 default:
663 break;
664 }
665 return ret;
666 }
667
668 static int
669 syncprov_findcsn( Operation *op, find_csn_t mode, struct berval *csn )
670 {
671 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
672 syncprov_info_t *si = on->on_bi.bi_private;
673
674 slap_callback cb = {0};
675 Operation fop;
676 SlapReply frs = { REP_RESULT };
677 char buf[LDAP_PVT_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
678 char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
679 struct berval maxcsn;
680 Filter cf;
681 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
682 fpres_cookie pcookie;
683 sync_control *srs = NULL;
684 struct slap_limits_set fc_limits;
685 int i, rc = LDAP_SUCCESS, findcsn_retry = 1;
686 int maxid;
687
688 if ( mode != FIND_MAXCSN ) {
689 srs = op->o_controls[slap_cids.sc_LDAPsync];
690 }
691
692 Debug( LDAP_DEBUG_SYNC, "%s syncprov_findcsn: mode=%s csn=%s\n",
693 op->o_log_prefix,
694 mode == FIND_MAXCSN ?
695 "FIND_MAXCSN" :
696 mode == FIND_CSN ?
697 "FIND_CSN" :
698 "FIND_PRESENT",
699 csn ? csn->bv_val : "" );
700
701 again:
702 fop = *op;
703 fop.o_sync_mode &= SLAP_CONTROL_MASK; /* turn off sync_mode */
704 /* We want pure entries, not referrals */
705 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
706
707 cf.f_ava = &eq;
708 cf.f_av_desc = slap_schema.si_ad_entryCSN;
709 BER_BVZERO( &cf.f_av_value );
710 cf.f_next = NULL;
711
712 fop.o_callback = &cb;
713 fop.ors_limit = NULL;
714 fop.ors_tlimit = SLAP_NO_LIMIT;
715 fop.ors_filter = &cf;
716 fop.ors_filterstr.bv_val = buf;
717
718 switch( mode ) {
719 case FIND_MAXCSN:
720 cf.f_choice = LDAP_FILTER_GE;
721 /* If there are multiple CSNs, use the one with our serverID */
722 for ( i=0; i<si->si_numcsns; i++) {
723 if ( slap_serverID == si->si_sids[i] ) {
724 maxid = i;
725 break;
726 }
727 }
728 if ( i == si->si_numcsns ) {
729 /* No match: this is multimaster, and none of the content in the DB
730 * originated locally. Treat like no CSN.
731 */
732 return LDAP_NO_SUCH_OBJECT;
733 }
734 cf.f_av_value = si->si_ctxcsn[maxid];
735 fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
736 "(entryCSN>=%s)", cf.f_av_value.bv_val );
737 if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
738 return LDAP_OTHER;
739 }
740 fop.ors_attrsonly = 0;
741 fop.ors_attrs = csn_anlist;
742 fop.ors_slimit = SLAP_NO_LIMIT;
743 cb.sc_private = &maxcsn;
744 cb.sc_response = findmax_cb;
745 strcpy( cbuf, cf.f_av_value.bv_val );
746 maxcsn.bv_val = cbuf;
747 maxcsn.bv_len = cf.f_av_value.bv_len;
748 break;
749 case FIND_CSN:
750 if ( BER_BVISEMPTY( &cf.f_av_value )) {
751 cf.f_av_value = *csn;
752 }
753 fop.o_dn = op->o_bd->be_rootdn;
754 fop.o_ndn = op->o_bd->be_rootndn;
755 fop.o_req_dn = op->o_bd->be_suffix[0];
756 fop.o_req_ndn = op->o_bd->be_nsuffix[0];
757 /* Look for exact match the first time */
758 if ( findcsn_retry ) {
759 cf.f_choice = LDAP_FILTER_EQUALITY;
760 fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
761 "(entryCSN=%s)", cf.f_av_value.bv_val );
762 /* On retry, look for <= */
763 } else {
764 cf.f_choice = LDAP_FILTER_LE;
765 fop.ors_limit = &fc_limits;
766 memset( &fc_limits, 0, sizeof( fc_limits ));
767 fc_limits.lms_s_unchecked = 1;
768 fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
769 "(entryCSN<=%s)", cf.f_av_value.bv_val );
770 }
771 if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
772 return LDAP_OTHER;
773 }
774 fop.ors_attrsonly = 1;
775 fop.ors_attrs = slap_anlist_no_attrs;
776 fop.ors_slimit = 1;
777 cb.sc_private = NULL;
778 cb.sc_response = findcsn_cb;
779 break;
780 case FIND_PRESENT:
781 fop.ors_filter = op->ors_filter;
782 fop.ors_filterstr = op->ors_filterstr;
783 fop.ors_attrsonly = 0;
784 fop.ors_attrs = uuid_anlist;
785 fop.ors_slimit = SLAP_NO_LIMIT;
786 cb.sc_private = &pcookie;
787 cb.sc_response = findpres_cb;
788 pcookie.num = 0;
789
790 /* preallocate storage for a full set */
791 pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
792 sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
793 op->o_tmpmemctx );
794 pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
795 pcookie.uuids[0].bv_val = pcookie.last;
796 pcookie.uuids[0].bv_len = UUID_LEN;
797 for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
798 pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
799 pcookie.uuids[i].bv_len = UUID_LEN;
800 }
801 break;
802 }
803
804 fop.o_bd->bd_info = (BackendInfo *)on->on_info;
805 fop.o_bd->be_search( &fop, &frs );
806 fop.o_bd->bd_info = (BackendInfo *)on;
807
808 switch( mode ) {
809 case FIND_MAXCSN:
810 if ( ber_bvcmp( &si->si_ctxcsn[maxid], &maxcsn )) {
811 #ifdef CHECK_CSN
812 Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
813 assert( !syn->ssyn_validate( syn, &maxcsn ));
814 #endif
815 ber_bvreplace( &si->si_ctxcsn[maxid], &maxcsn );
816 si->si_numops++; /* ensure a checkpoint */
817 }
818 break;
819 case FIND_CSN:
820 /* If matching CSN was not found, invalidate the context. */
821 Debug( LDAP_DEBUG_SYNC, "%s syncprov_findcsn: csn%s=%s %sfound\n",
822 op->o_log_prefix,
823 cf.f_choice == LDAP_FILTER_EQUALITY ? "=" : "<",
824 cf.f_av_value.bv_val, cb.sc_private ? "" : "not " );
825 if ( !cb.sc_private ) {
826 /* If we didn't find an exact match, then try for <= */
827 if ( findcsn_retry ) {
828 findcsn_retry = 0;
829 rs_reinit( &frs, REP_RESULT );
830 goto again;
831 }
832 rc = LDAP_NO_SUCH_OBJECT;
833 }
834 break;
835 case FIND_PRESENT:
836 op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
837 break;
838 }
839
840 return rc;
841 }
842
843 static void free_resinfo( syncres *sr )
844 {
845 syncres **st;
846 resinfo *ri = sr->s_info;
847 int freeit = 0;
848
849 ldap_pvt_thread_mutex_lock( &ri->ri_mutex );
850 for (st = &sr->s_info->ri_list; *st; st = &(*st)->s_rilist) {
851 if (*st == sr) {
852 *st = sr->s_rilist;
853 if ( !sr->s_info->ri_list )
854 freeit = 1;
855 sr->s_info = NULL;
856 break;
857 }
858 }
859 ldap_pvt_thread_mutex_unlock( &ri->ri_mutex );
860 if ( freeit ) {
861 ldap_pvt_thread_mutex_destroy( &ri->ri_mutex );
862 if ( ri->ri_e )
863 entry_free( ri->ri_e );
864 if ( !BER_BVISNULL( &ri->ri_cookie ))
865 ch_free( ri->ri_cookie.bv_val );
866 ch_free( ri );
867 }
868 }
869
870 #define FS_UNLINK 1
871 #define FS_LOCK 2
872 #define FS_DEFER 4
873
874 #define FSR_NOTFREE 0
875 #define FSR_DIDFREE 1
876 #define FSR_CANFREE 2
877
878 static int
879 syncprov_free_syncop( syncops *so, int flags )
880 {
881 syncres *sr, *srnext;
882 GroupAssertion *ga, *gnext;
883
884 if ( flags & FS_LOCK )
885 ldap_pvt_thread_mutex_lock( &so->s_mutex );
886 /* already being freed, or still in use */
887 if ( !so->s_inuse || so->s_inuse > 1 ) {
888 if ( flags & FS_LOCK )
889 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
890 if ( !( flags & FS_DEFER ) && so->s_inuse )
891 so->s_inuse--;
892 return FSR_NOTFREE;
893 }
894 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
895
896 /* caller wants to cleanup other stuff before actual free */
897 if ( flags & FS_DEFER )
898 return FSR_CANFREE;
899
900 if (( flags & FS_UNLINK ) && so->s_si ) {
901 syncops **sop;
902 ldap_pvt_thread_mutex_lock( &so->s_si->si_ops_mutex );
903 for ( sop = &so->s_si->si_ops; *sop; sop = &(*sop)->s_next ) {
904 if ( *sop == so ) {
905 *sop = so->s_next;
906 break;
907 }
908 }
909 ldap_pvt_thread_mutex_unlock( &so->s_si->si_ops_mutex );
910 }
911 if ( so->s_flags & PS_IS_DETACHED ) {
912 filter_free( so->s_op->ors_filter );
913 for ( ga = so->s_op->o_groups; ga; ga=gnext ) {
914 gnext = ga->ga_next;
915 ch_free( ga );
916 }
917 ch_free( so->s_op );
918 }
919 ch_free( so->s_base.bv_val );
920 for ( sr=so->s_res; sr; sr=srnext ) {
921 srnext = sr->s_next;
922 free_resinfo( sr );
923 ch_free( sr );
924 }
925 ldap_pvt_thread_mutex_destroy( &so->s_mutex );
926 ch_free( so );
927 return FSR_DIDFREE;
928 }
929
930 /* Send a persistent search response */
931 static int
932 syncprov_sendresp( Operation *op, resinfo *ri, syncops *so, int mode )
933 {
934 SlapReply rs = { REP_SEARCH };
935 struct berval cookie, csns[2];
936 Entry e_uuid = {0};
937 Attribute a_uuid = {0};
938
939 if ( so->s_op->o_abandon )
940 return SLAPD_ABANDON;
941
942 rs.sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2, op->o_tmpmemctx );
943 rs.sr_ctrls[1] = NULL;
944 rs.sr_flags = REP_CTRLS_MUSTBEFREED;
945 csns[0] = ri->ri_csn;
946 BER_BVZERO( &csns[1] );
947 slap_compose_sync_cookie( op, &cookie, csns, so->s_rid,
948 slap_serverID ? slap_serverID : -1, NULL );
949
950 #ifdef LDAP_DEBUG
951 if ( so->s_sid > 0 ) {
952 Debug( LDAP_DEBUG_SYNC, "%s syncprov_sendresp: to=%03x, cookie=%s\n",
953 op->o_log_prefix, so->s_sid, cookie.bv_val );
954 } else {
955 Debug( LDAP_DEBUG_SYNC, "%s syncprov_sendresp: cookie=%s\n",
956 op->o_log_prefix, cookie.bv_val );
957 }
958 #endif
959
960 e_uuid.e_attrs = &a_uuid;
961 a_uuid.a_desc = slap_schema.si_ad_entryUUID;
962 a_uuid.a_nvals = &ri->ri_uuid;
963 rs.sr_err = syncprov_state_ctrl( op, &rs, &e_uuid,
964 mode, rs.sr_ctrls, 0, 1, &cookie );
965 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
966
967 rs.sr_entry = &e_uuid;
968 if ( mode == LDAP_SYNC_ADD || mode == LDAP_SYNC_MODIFY ) {
969 e_uuid = *ri->ri_e;
970 e_uuid.e_private = NULL;
971 }
972
973 switch( mode ) {
974 case LDAP_SYNC_ADD:
975 if ( ri->ri_isref && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
976 rs.sr_ref = get_entry_referrals( op, rs.sr_entry );
977 rs.sr_err = send_search_reference( op, &rs );
978 ber_bvarray_free( rs.sr_ref );
979 break;
980 }
981 /* fallthru */
982 case LDAP_SYNC_MODIFY:
983 Debug( LDAP_DEBUG_SYNC, "%s syncprov_sendresp: sending %s, dn=%s\n",
984 op->o_log_prefix,
985 mode == LDAP_SYNC_ADD ? "LDAP_SYNC_ADD" : "LDAP_SYNC_MODIFY",
986 e_uuid.e_nname.bv_val );
987 rs.sr_attrs = op->ors_attrs;
988 rs.sr_err = send_search_entry( op, &rs );
989 break;
990 case LDAP_SYNC_DELETE:
991 Debug( LDAP_DEBUG_SYNC, "%s syncprov_sendresp: "
992 "sending LDAP_SYNC_DELETE, dn=%s\n",
993 op->o_log_prefix, ri->ri_dn.bv_val );
994 e_uuid.e_attrs = NULL;
995 e_uuid.e_name = ri->ri_dn;
996 e_uuid.e_nname = ri->ri_ndn;
997 if ( ri->ri_isref && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
998 struct berval bv = BER_BVNULL;
999 rs.sr_ref = &bv;
1000 rs.sr_err = send_search_reference( op, &rs );
1001 } else {
1002 rs.sr_err = send_search_entry( op, &rs );
1003 }
1004 break;
1005 default:
1006 assert(0);
1007 }
1008 return rs.sr_err;
1009 }
1010
1011 static void
1012 syncprov_qstart( syncops *so );
1013
1014 /* Play back queued responses */
1015 static int
1016 syncprov_qplay( Operation *op, syncops *so )
1017 {
1018 syncres *sr;
1019 int rc = 0;
1020
1021 do {
1022 ldap_pvt_thread_mutex_lock( &so->s_mutex );
1023 sr = so->s_res;
1024 /* Exit loop with mutex held */
1025 if ( !sr )
1026 break;
1027 so->s_res = sr->s_next;
1028 if ( !so->s_res )
1029 so->s_restail = NULL;
1030 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
1031
1032 if ( !so->s_op->o_abandon ) {
1033
1034 if ( sr->s_mode == LDAP_SYNC_NEW_COOKIE ) {
1035 SlapReply rs = { REP_INTERMEDIATE };
1036
1037 rc = syncprov_sendinfo( op, &rs, LDAP_TAG_SYNC_NEW_COOKIE,
1038 &sr->s_info->ri_cookie, 0, NULL, 0 );
1039 } else {
1040 rc = syncprov_sendresp( op, sr->s_info, so, sr->s_mode );
1041 }
1042 } else {
1043 /* set rc so we don't do a new qstart */
1044 rc = 1;
1045 }
1046
1047 free_resinfo( sr );
1048 ch_free( sr );
1049
1050 if ( so->s_op->o_abandon )
1051 continue;
1052
1053 /* Exit loop with mutex held */
1054 ldap_pvt_thread_mutex_lock( &so->s_mutex );
1055 break;
1056
1057 } while (1);
1058
1059 /* We now only send one change at a time, to prevent one
1060 * psearch from hogging all the CPU. Resubmit this task if
1061 * there are more responses queued and no errors occurred.
1062 */
1063
1064 if ( rc == 0 && so->s_res ) {
1065 syncprov_qstart( so );
1066 }
1067
1068 return rc;
1069 }
1070
1071 static int
1072 syncprov_drop_psearch( syncops *so, int lock );
1073
1074 /* task for playing back queued responses */
1075 static void *
1076 syncprov_qtask( void *ctx, void *arg )
1077 {
1078 syncops *so = arg;
1079 OperationBuffer opbuf;
1080 Operation *op;
1081 BackendDB be;
1082 int rc, flag, frc;
1083
1084 op = &opbuf.ob_op;
1085 *op = *so->s_op;
1086 op->o_hdr = &opbuf.ob_hdr;
1087 op->o_controls = opbuf.ob_controls;
1088 memset( op->o_controls, 0, sizeof(opbuf.ob_controls) );
1089 op->o_sync = SLAP_CONTROL_IGNORED;
1090
1091 *op->o_hdr = *so->s_op->o_hdr;
1092
1093 op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx, 1);
1094 op->o_tmpmfuncs = &slap_sl_mfuncs;
1095 op->o_threadctx = ctx;
1096 operation_counter_init( op, ctx );
1097
1098 /* syncprov_qplay expects a fake db */
1099 be = *so->s_op->o_bd;
1100 be.be_flags |= SLAP_DBFLAG_OVERLAY;
1101 op->o_bd = &be;
1102 LDAP_SLIST_FIRST(&op->o_extra) = NULL;
1103 op->o_callback = NULL;
1104
1105 rc = syncprov_qplay( op, so );
1106
1107 /* if an error occurred, or no responses left, task is no longer queued */
1108 if ( !rc && !so->s_res )
1109 rc = 1;
1110
1111 flag = FS_UNLINK;
1112 if ( rc && op->o_abandon )
1113 flag = FS_DEFER;
1114
1115 /* decrement use count... */
1116 frc = syncprov_free_syncop( so, flag );
1117 if ( frc == FSR_NOTFREE ) {
1118 if ( rc )
1119 /* if we didn't unlink, and task is no longer queued, clear flag */
1120 so->s_flags ^= PS_TASK_QUEUED;
1121 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
1122 }
1123
1124 /* if we got abandoned while processing, cleanup now */
1125 if ( frc == FSR_CANFREE ) {
1126 syncprov_drop_psearch( so, 1 );
1127 }
1128
1129 return NULL;
1130 }
1131
1132 /* Start the task to play back queued psearch responses */
1133 static void
1134 syncprov_qstart( syncops *so )
1135 {
1136 so->s_flags |= PS_TASK_QUEUED;
1137 so->s_inuse++;
1138 ldap_pvt_thread_pool_submit2( &connection_pool,
1139 syncprov_qtask, so, &so->s_pool_cookie );
1140 }
1141
1142 /* Queue a persistent search response */
1143 static int
1144 syncprov_qresp( opcookie *opc, syncops *so, int mode )
1145 {
1146 syncres *sr;
1147 resinfo *ri;
1148 int srsize;
1149 struct berval csn = opc->sctxcsn;
1150
1151 sr = ch_malloc( sizeof( syncres ));
1152 sr->s_next = NULL;
1153 sr->s_mode = mode;
1154 if ( !opc->ssres.s_info ) {
1155
1156 srsize = sizeof( resinfo );
1157 if ( csn.bv_len )
1158 srsize += csn.bv_len + 1;
1159
1160 if ( opc->se ) {
1161 Attribute *a;
1162 ri = ch_malloc( srsize );
1163 ri->ri_dn = opc->se->e_name;
1164 ri->ri_ndn = opc->se->e_nname;
1165 a = attr_find( opc->se->e_attrs, slap_schema.si_ad_entryUUID );
1166 if ( a )
1167 ri->ri_uuid = a->a_nvals[0];
1168 else
1169 ri->ri_uuid.bv_len = 0;
1170 if ( csn.bv_len ) {
1171 ri->ri_csn.bv_val = (char *)(ri + 1);
1172 ri->ri_csn.bv_len = csn.bv_len;
1173 memcpy( ri->ri_csn.bv_val, csn.bv_val, csn.bv_len );
1174 ri->ri_csn.bv_val[csn.bv_len] = '\0';
1175 } else {
1176 ri->ri_csn.bv_val = NULL;
1177 }
1178 } else {
1179 srsize += opc->suuid.bv_len +
1180 opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1;
1181 ri = ch_malloc( srsize );
1182 ri->ri_dn.bv_val = (char *)(ri + 1);
1183 ri->ri_dn.bv_len = opc->sdn.bv_len;
1184 ri->ri_ndn.bv_val = lutil_strcopy( ri->ri_dn.bv_val,
1185 opc->sdn.bv_val ) + 1;
1186 ri->ri_ndn.bv_len = opc->sndn.bv_len;
1187 ri->ri_uuid.bv_val = lutil_strcopy( ri->ri_ndn.bv_val,
1188 opc->sndn.bv_val ) + 1;
1189 ri->ri_uuid.bv_len = opc->suuid.bv_len;
1190 AC_MEMCPY( ri->ri_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1191 if ( csn.bv_len ) {
1192 ri->ri_csn.bv_val = ri->ri_uuid.bv_val + ri->ri_uuid.bv_len;
1193 memcpy( ri->ri_csn.bv_val, csn.bv_val, csn.bv_len );
1194 ri->ri_csn.bv_val[csn.bv_len] = '\0';
1195 } else {
1196 ri->ri_csn.bv_val = NULL;
1197 }
1198 }
1199 ri->ri_list = &opc->ssres;
1200 ri->ri_e = opc->se;
1201 ri->ri_csn.bv_len = csn.bv_len;
1202 ri->ri_isref = opc->sreference;
1203 BER_BVZERO( &ri->ri_cookie );
1204 ldap_pvt_thread_mutex_init( &ri->ri_mutex );
1205 opc->se = NULL;
1206 opc->ssres.s_info = ri;
1207 }
1208 ri = opc->ssres.s_info;
1209 sr->s_info = ri;
1210 ldap_pvt_thread_mutex_lock( &ri->ri_mutex );
1211 sr->s_rilist = ri->ri_list;
1212 ri->ri_list = sr;
1213 if ( mode == LDAP_SYNC_NEW_COOKIE && BER_BVISNULL( &ri->ri_cookie )) {
1214 syncprov_info_t *si = opc->son->on_bi.bi_private;
1215
1216 slap_compose_sync_cookie( NULL, &ri->ri_cookie, si->si_ctxcsn,
1217 so->s_rid, slap_serverID ? slap_serverID : -1, NULL );
1218 }
1219 Debug( LDAP_DEBUG_SYNC, "%s syncprov_qresp: "
1220 "set up a new syncres mode=%d csn=%s\n",
1221 so->s_op->o_log_prefix, mode, csn.bv_val ? csn.bv_val : "" );
1222 ldap_pvt_thread_mutex_unlock( &ri->ri_mutex );
1223
1224 ldap_pvt_thread_mutex_lock( &so->s_mutex );
1225 if ( !so->s_res ) {
1226 so->s_res = sr;
1227 } else {
1228 so->s_restail->s_next = sr;
1229 }
1230 so->s_restail = sr;
1231
1232 /* If the base of the psearch was modified, check it next time round */
1233 if ( so->s_flags & PS_WROTE_BASE ) {
1234 so->s_flags ^= PS_WROTE_BASE;
1235 so->s_flags |= PS_FIND_BASE;
1236 }
1237 if (( so->s_flags & (PS_IS_DETACHED|PS_TASK_QUEUED)) == PS_IS_DETACHED ) {
1238 syncprov_qstart( so );
1239 }
1240 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
1241 return LDAP_SUCCESS;
1242 }
1243
1244 static int
1245 syncprov_drop_psearch( syncops *so, int lock )
1246 {
1247 if ( so->s_flags & PS_IS_DETACHED ) {
1248 if ( lock )
1249 ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
1250 so->s_op->o_conn->c_n_ops_executing--;
1251 so->s_op->o_conn->c_n_ops_completed++;
1252 LDAP_STAILQ_REMOVE( &so->s_op->o_conn->c_ops, so->s_op, Operation,
1253 o_next );
1254 if ( lock )
1255 ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
1256 }
1257 return syncprov_free_syncop( so, FS_LOCK );
1258 }
1259
1260 static int
1261 syncprov_ab_cleanup( Operation *op, SlapReply *rs )
1262 {
1263 slap_callback *sc = op->o_callback;
1264 op->o_callback = sc->sc_next;
1265 syncprov_drop_psearch( sc->sc_private, 0 );
1266 op->o_tmpfree( sc, op->o_tmpmemctx );
1267 return 0;
1268 }
1269
1270 static int
1271 syncprov_op_abandon( Operation *op, SlapReply *rs )
1272 {
1273 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1274 syncprov_info_t *si = on->on_bi.bi_private;
1275 syncops *so, **sop;
1276
1277 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1278 for ( sop=&si->si_ops; (so = *sop); sop = &(*sop)->s_next ) {
1279 if ( so->s_op->o_connid == op->o_connid &&
1280 so->s_op->o_msgid == op->orn_msgid ) {
1281 so->s_op->o_abandon = 1;
1282 *sop = so->s_next;
1283 break;
1284 }
1285 }
1286 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1287 if ( so ) {
1288 /* Is this really a Cancel exop? */
1289 if ( op->o_tag != LDAP_REQ_ABANDON ) {
1290 so->s_op->o_cancel = SLAP_CANCEL_ACK;
1291 rs->sr_err = LDAP_CANCELLED;
1292 send_ldap_result( so->s_op, rs );
1293 if ( so->s_flags & PS_IS_DETACHED ) {
1294 slap_callback *cb;
1295 cb = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
1296 cb->sc_cleanup = syncprov_ab_cleanup;
1297 cb->sc_next = op->o_callback;
1298 cb->sc_private = so;
1299 op->o_callback = cb;
1300 return SLAP_CB_CONTINUE;
1301 }
1302 }
1303 /* if task is active, it must drop itself */
1304 if ( !( so->s_flags & PS_TASK_QUEUED ))
1305 syncprov_drop_psearch( so, 0 );
1306 }
1307 return SLAP_CB_CONTINUE;
1308 }
1309
1310 /* Find which persistent searches are affected by this operation */
1311 static void
1312 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
1313 {
1314 slap_overinst *on = opc->son;
1315 syncprov_info_t *si = on->on_bi.bi_private;
1316
1317 fbase_cookie fc;
1318 syncops **pss;
1319 Entry *e = NULL;
1320 Attribute *a;
1321 int rc, gonext;
1322 BackendDB *b0 = op->o_bd, db;
1323
1324 fc.fdn = saveit ? &op->o_req_ndn : &opc->sndn;
1325 if ( !saveit && op->o_tag == LDAP_REQ_DELETE ) {
1326 /* Delete succeeded, there is no entry */
1327 } else if ( op->o_tag != LDAP_REQ_ADD ) {
1328 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1329 db = *op->o_bd;
1330 op->o_bd = &db;
1331 }
1332 rc = overlay_entry_get_ov( op, fc.fdn, NULL, NULL, 0, &e, on );
1333 /* If we're sending responses now, make a copy and unlock the DB */
1334 if ( e && !saveit ) {
1335 if ( !opc->se )
1336 opc->se = entry_dup( e );
1337 overlay_entry_release_ov( op, e, 0, on );
1338 e = opc->se;
1339 }
1340 if ( rc ) {
1341 Debug( LDAP_DEBUG_SYNC, "%s syncprov_matchops: "
1342 "%s check, error finding entry dn=%s in database\n",
1343 op->o_log_prefix, saveit ? "initial" : "final", fc.fdn->bv_val );
1344 op->o_bd = b0;
1345 return;
1346 }
1347 } else {
1348 e = op->ora_e;
1349 if ( !saveit ) {
1350 if ( !opc->se )
1351 opc->se = entry_dup( e );
1352 e = opc->se;
1353 }
1354 }
1355
1356 if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
1357 if ( op->o_tag == LDAP_REQ_MODRDN ) {
1358 ber_dupbv_x( &opc->sdn, &op->orr_newDN, op->o_tmpmemctx );
1359 ber_dupbv_x( &opc->sndn, &op->orr_nnewDN, op->o_tmpmemctx );
1360 } else {
1361 ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
1362 ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
1363 }
1364 opc->sreference = is_entry_referral( e );
1365 a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
1366 if ( a )
1367 ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
1368 Debug( LDAP_DEBUG_SYNC, "%s syncprov_matchops: "
1369 "%srecording uuid for dn=%s on opc=%p\n",
1370 op->o_log_prefix, a ? "" : "not ", opc->sdn.bv_val, opc );
1371 }
1372
1373 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1374 for (pss = &si->si_ops; *pss; pss = gonext ? &(*pss)->s_next : pss)
1375 {
1376 Operation op2;
1377 Opheader oh;
1378 syncmatches *sm;
1379 int found = 0;
1380 syncops *snext, *ss = *pss;
1381
1382 gonext = 1;
1383 if ( ss->s_op->o_abandon )
1384 continue;
1385
1386 /* Don't send ops back to the originator */
1387 if ( opc->osid > 0 && opc->osid == ss->s_sid ) {
1388 Debug( LDAP_DEBUG_SYNC, "%s syncprov_matchops: "
1389 "skipping original sid %03x\n",
1390 ss->s_op->o_log_prefix, opc->osid );
1391 continue;
1392 }
1393
1394 /* Don't send ops back to the messenger */
1395 if ( opc->rsid > 0 && opc->rsid == ss->s_sid ) {
1396 Debug( LDAP_DEBUG_SYNC, "%s syncprov_matchops: "
1397 "skipping relayed sid %03x\n",
1398 ss->s_op->o_log_prefix, opc->rsid );
1399 continue;
1400 }
1401
1402 /* validate base */
1403 fc.fss = ss;
1404 fc.fbase = 0;
1405 fc.fscope = 0;
1406
1407 /* If the base of the search is missing, signal a refresh */
1408 rc = syncprov_findbase( op, &fc );
1409 if ( rc != LDAP_SUCCESS ) {
1410 SlapReply rs = {REP_RESULT};
1411 send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
1412 "search base has changed" );
1413 snext = ss->s_next;
1414 if ( syncprov_drop_psearch( ss, 1 ) )
1415 *pss = snext;
1416 gonext = 0;
1417 continue;
1418 }
1419
1420 /* If we're sending results now, look for this op in old matches */
1421 if ( !saveit ) {
1422 syncmatches *old;
1423
1424 /* Did we modify the search base? */
1425 if ( dn_match( &op->o_req_ndn, &ss->s_base )) {
1426 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1427 ss->s_flags |= PS_WROTE_BASE;
1428 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1429 }
1430
1431 for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
1432 old=sm, sm=sm->sm_next ) {
1433 if ( sm->sm_op == ss ) {
1434 found = 1;
1435 old->sm_next = sm->sm_next;
1436 op->o_tmpfree( sm, op->o_tmpmemctx );
1437 break;
1438 }
1439 }
1440 }
1441
1442 rc = LDAP_COMPARE_FALSE;
1443 if ( e && !is_entry_glue( e ) && fc.fscope ) {
1444 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1445 op2 = *ss->s_op;
1446 oh = *op->o_hdr;
1447 oh.oh_conn = ss->s_op->o_conn;
1448 oh.oh_connid = ss->s_op->o_connid;
1449 op2.o_bd = op->o_bd->bd_self;
1450 op2.o_hdr = &oh;
1451 op2.o_extra = op->o_extra;
1452 op2.o_callback = NULL;
1453 if (ss->s_flags & PS_FIX_FILTER) {
1454 /* Skip the AND/GE clause that we stuck on in front. We
1455 would lose deletes/mods that happen during the refresh
1456 phase otherwise (ITS#6555) */
1457 op2.ors_filter = ss->s_op->ors_filter->f_and->f_next;
1458 }
1459 rc = test_filter( &op2, e, op2.ors_filter );
1460 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1461 }
1462
1463 Debug( LDAP_DEBUG_TRACE, "%s syncprov_matchops: "
1464 "sid %03x fscope %d rc %d\n",
1465 ss->s_op->o_log_prefix, ss->s_sid, fc.fscope, rc );
1466
1467 /* check if current o_req_dn is in scope and matches filter */
1468 if ( fc.fscope && rc == LDAP_COMPARE_TRUE ) {
1469 if ( saveit ) {
1470 sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
1471 sm->sm_next = opc->smatches;
1472 sm->sm_op = ss;
1473 ldap_pvt_thread_mutex_lock( &ss->s_mutex );
1474 ++ss->s_inuse;
1475 ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
1476 opc->smatches = sm;
1477 } else {
1478 /* if found send UPDATE else send ADD */
1479 syncprov_qresp( opc, ss,
1480 found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD );
1481 }
1482 } else if ( !saveit && found ) {
1483 /* send DELETE */
1484 syncprov_qresp( opc, ss, LDAP_SYNC_DELETE );
1485 } else if ( !saveit ) {
1486 syncprov_qresp( opc, ss, LDAP_SYNC_NEW_COOKIE );
1487 }
1488 if ( !saveit && found ) {
1489 /* Decrement s_inuse, was incremented when called
1490 * with saveit == TRUE
1491 */
1492 snext = ss->s_next;
1493 if ( syncprov_free_syncop( ss, FS_LOCK ) ) {
1494 *pss = snext;
1495 gonext = 0;
1496 }
1497 }
1498 }
1499 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1500
1501 if ( op->o_tag != LDAP_REQ_ADD && e ) {
1502 if ( !SLAP_ISOVERLAY( op->o_bd )) {
1503 op->o_bd = &db;
1504 }
1505 if ( saveit )
1506 overlay_entry_release_ov( op, e, 0, on );
1507 op->o_bd = b0;
1508 }
1509 if ( !saveit ) {
1510 if ( opc->ssres.s_info )
1511 free_resinfo( &opc->ssres );
1512 else if ( opc->se )
1513 entry_free( opc->se );
1514 }
1515 op->o_bd = b0;
1516 }
1517
1518 static int
1519 syncprov_op_cleanup( Operation *op, SlapReply *rs )
1520 {
1521 slap_callback *cb = op->o_callback;
1522 opcookie *opc = cb->sc_private;
1523 slap_overinst *on = opc->son;
1524 syncprov_info_t *si = on->on_bi.bi_private;
1525 syncmatches *sm, *snext;
1526 modtarget *mt;
1527
1528 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
1529 if ( si->si_active )
1530 si->si_active--;
1531 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
1532
1533 for (sm = opc->smatches; sm; sm=snext) {
1534 snext = sm->sm_next;
1535 syncprov_free_syncop( sm->sm_op, FS_LOCK|FS_UNLINK );
1536 op->o_tmpfree( sm, op->o_tmpmemctx );
1537 }
1538
1539 /* Remove op from lock table */
1540 mt = opc->smt;
1541 if ( mt ) {
1542 modinst *mi = (modinst *)(opc+1), **m2;
1543 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
1544 for (m2 = &mt->mt_mods; ; m2 = &(*m2)->mi_next) {
1545 if ( *m2 == mi ) {
1546 *m2 = mi->mi_next;
1547 if ( mt->mt_tail == mi )
1548 mt->mt_tail = ( m2 == &mt->mt_mods ) ? NULL : (modinst *)m2;
1549 break;
1550 }
1551 }
1552 /* If there are more, promote the next one */
1553 if ( mt->mt_mods ) {
1554 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1555 } else {
1556 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
1557 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
1558 ldap_avl_delete( &si->si_mods, mt, sp_avl_cmp );
1559 ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
1560 ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
1561 ch_free( mt->mt_dn.bv_val );
1562 ch_free( mt );
1563 }
1564 }
1565 if ( !BER_BVISNULL( &opc->suuid ))
1566 op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
1567 if ( !BER_BVISNULL( &opc->sndn ))
1568 op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
1569 if ( !BER_BVISNULL( &opc->sdn ))
1570 op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
1571 op->o_callback = cb->sc_next;
1572
1573 if ( opc->ssres.s_info ) {
1574 free_resinfo( &opc->ssres );
1575 }
1576 op->o_tmpfree(cb, op->o_tmpmemctx);
1577
1578 return 0;
1579 }
1580
1581 static void
1582 syncprov_checkpoint( Operation *op, slap_overinst *on )
1583 {
1584 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
1585 Modifications mod;
1586 Operation opm;
1587 SlapReply rsm = {REP_RESULT};
1588 slap_callback cb = {0};
1589 BackendDB be;
1590 BackendInfo *bi;
1591
1592 #ifdef CHECK_CSN
1593 Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
1594
1595 int i;
1596 for ( i=0; i<si->si_numcsns; i++ ) {
1597 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1598 }
1599 #endif
1600
1601 Debug( LDAP_DEBUG_SYNC, "%s syncprov_checkpoint: running checkpoint\n",
1602 op->o_log_prefix );
1603
1604 mod.sml_numvals = si->si_numcsns;
1605 mod.sml_values = si->si_ctxcsn;
1606 mod.sml_nvalues = NULL;
1607 mod.sml_desc = slap_schema.si_ad_contextCSN;
1608 mod.sml_op = LDAP_MOD_REPLACE;
1609 mod.sml_flags = SLAP_MOD_INTERNAL;
1610 mod.sml_next = NULL;
1611
1612 cb.sc_response = slap_null_cb;
1613 opm = *op;
1614 opm.o_tag = LDAP_REQ_MODIFY;
1615 opm.o_callback = &cb;
1616 opm.orm_modlist = &mod;
1617 opm.orm_no_opattrs = 1;
1618 if ( SLAP_GLUE_SUBORDINATE( op->o_bd )) {
1619 be = *on->on_info->oi_origdb;
1620 opm.o_bd = &be;
1621 }
1622 opm.o_req_dn = si->si_contextdn;
1623 opm.o_req_ndn = si->si_contextdn;
1624 bi = opm.o_bd->bd_info;
1625 opm.o_bd->bd_info = on->on_info->oi_orig;
1626 opm.o_managedsait = SLAP_CONTROL_NONCRITICAL;
1627 opm.o_no_schema_check = 1;
1628 opm.o_dont_replicate = 1;
1629 opm.o_opid = -1;
1630 opm.o_bd->be_modify( &opm, &rsm );
1631
1632 if ( rsm.sr_err == LDAP_NO_SUCH_OBJECT &&
1633 SLAP_SYNC_SUBENTRY( opm.o_bd )) {
1634 const char *text;
1635 char txtbuf[SLAP_TEXT_BUFLEN];
1636 size_t textlen = sizeof txtbuf;
1637 Entry *e = slap_create_context_csn_entry( opm.o_bd, NULL );
1638 rs_reinit( &rsm, REP_RESULT );
1639 slap_mods2entry( &mod, &e, 0, 1, &text, txtbuf, textlen);
1640 opm.ora_e = e;
1641 opm.o_bd->be_add( &opm, &rsm );
1642 if ( e == opm.ora_e )
1643 be_entry_release_w( &opm, opm.ora_e );
1644 }
1645 opm.o_bd->bd_info = bi;
1646
1647 if ( mod.sml_next != NULL ) {
1648 slap_mods_free( mod.sml_next, 1 );
1649 }
1650 #ifdef CHECK_CSN
1651 for ( i=0; i<si->si_numcsns; i++ ) {
1652 assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
1653 }
1654 #endif
1655 }
1656
1657 static void
1658 syncprov_add_slog( Operation *op )
1659 {
1660 opcookie *opc = op->o_callback->sc_private;
1661 slap_overinst *on = opc->son;
1662 syncprov_info_t *si = on->on_bi.bi_private;
1663 sessionlog *sl;
1664 slog_entry *se;
1665 char uuidstr[40];
1666 int rc;
1667
1668 sl = si->si_logs;
1669 {
1670 if ( BER_BVISEMPTY( &op->o_csn ) ) {
1671 /* During the syncrepl refresh phase we can receive operations
1672 * without a csn. We cannot reliably determine the consumers
1673 * state with respect to such operations, so we ignore them and
1674 * wipe out anything in the log if we see them.
1675 */
1676 ldap_pvt_thread_rdwr_wlock( &sl->sl_mutex );
1677 /* can only do this if no one else is reading the log at the moment */
1678 if ( !sl->sl_playing ) {
1679 ldap_tavl_free( sl->sl_entries, (AVL_FREE)ch_free );
1680 sl->sl_num = 0;
1681 sl->sl_entries = NULL;
1682 }
1683 ldap_pvt_thread_rdwr_wunlock( &sl->sl_mutex );
1684 return;
1685 }
1686
1687 /* Allocate a record. UUIDs are not NUL-terminated. */
1688 se = ch_malloc( sizeof( slog_entry ) + opc->suuid.bv_len +
1689 op->o_csn.bv_len + 1 );
1690 se->se_tag = op->o_tag;
1691
1692 se->se_uuid.bv_val = (char *)(&se[1]);
1693 AC_MEMCPY( se->se_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
1694 se->se_uuid.bv_len = opc->suuid.bv_len;
1695
1696 se->se_csn.bv_val = se->se_uuid.bv_val + opc->suuid.bv_len;
1697 AC_MEMCPY( se->se_csn.bv_val, op->o_csn.bv_val, op->o_csn.bv_len );
1698 se->se_csn.bv_val[op->o_csn.bv_len] = '\0';
1699 se->se_csn.bv_len = op->o_csn.bv_len;
1700 se->se_sid = slap_parse_csn_sid( &se->se_csn );
1701
1702 ldap_pvt_thread_rdwr_wlock( &sl->sl_mutex );
1703 if ( LogTest( LDAP_DEBUG_SYNC ) ) {
1704 uuidstr[0] = 0;
1705 if ( !BER_BVISEMPTY( &opc->suuid ) ) {
1706 lutil_uuidstr_from_normalized( opc->suuid.bv_val, opc->suuid.bv_len,
1707 uuidstr, 40 );
1708 }
1709 Debug( LDAP_DEBUG_SYNC, "%s syncprov_add_slog: "
1710 "adding csn=%s to sessionlog, uuid=%s\n",
1711 op->o_log_prefix, se->se_csn.bv_val, uuidstr );
1712 }
1713 if ( !sl->sl_entries ) {
1714 if ( !sl->sl_mincsn ) {
1715 sl->sl_numcsns = 1;
1716 sl->sl_mincsn = ch_malloc( 2*sizeof( struct berval ));
1717 sl->sl_sids = ch_malloc( sizeof( int ));
1718 sl->sl_sids[0] = se->se_sid;
1719 ber_dupbv( sl->sl_mincsn, &se->se_csn );
1720 BER_BVZERO( &sl->sl_mincsn[1] );
1721 }
1722 }
1723 rc = ldap_tavl_insert( &sl->sl_entries, se, syncprov_sessionlog_cmp, ldap_avl_dup_error );
1724 if ( rc ) {
1725 Debug( LDAP_DEBUG_SYNC, "%s syncprov_add_slog: "
1726 "duplicate sessionlog entry ignored: csn=%s, uuid=%s\n",
1727 op->o_log_prefix, se->se_csn.bv_val, uuidstr );
1728 ch_free( se );
1729 goto leave;
1730 }
1731 sl->sl_num++;
1732 if ( !sl->sl_playing && sl->sl_num > sl->sl_size ) {
1733 TAvlnode *edge = ldap_tavl_end( sl->sl_entries, TAVL_DIR_LEFT );
1734 while ( sl->sl_num > sl->sl_size ) {
1735 int i;
1736 TAvlnode *next = ldap_tavl_next( edge, TAVL_DIR_RIGHT );
1737 se = edge->avl_data;
1738 Debug( LDAP_DEBUG_SYNC, "%s syncprov_add_slog: "
1739 "expiring csn=%s from sessionlog (sessionlog size=%d)\n",
1740 op->o_log_prefix, se->se_csn.bv_val, sl->sl_num );
1741 for ( i=0; i<sl->sl_numcsns; i++ )
1742 if ( sl->sl_sids[i] >= se->se_sid )
1743 break;
1744 if ( i == sl->sl_numcsns || sl->sl_sids[i] != se->se_sid ) {
1745 Debug( LDAP_DEBUG_SYNC, "%s syncprov_add_slog: "
1746 "adding csn=%s to mincsn\n",
1747 op->o_log_prefix, se->se_csn.bv_val );
1748 slap_insert_csn_sids( (struct sync_cookie *)sl,
1749 i, se->se_sid, &se->se_csn );
1750 } else {
1751 Debug( LDAP_DEBUG_SYNC, "%s syncprov_add_slog: "
1752 "updating mincsn for sid=%d csn=%s to %s\n",
1753 op->o_log_prefix, se->se_sid, sl->sl_mincsn[i].bv_val, se->se_csn.bv_val );
1754 ber_bvreplace( &sl->sl_mincsn[i], &se->se_csn );
1755 }
1756 ldap_tavl_delete( &sl->sl_entries, se, syncprov_sessionlog_cmp );
1757 ch_free( se );
1758 edge = next;
1759 sl->sl_num--;
1760 }
1761 }
1762 leave:
1763 ldap_pvt_thread_rdwr_wunlock( &sl->sl_mutex );
1764 }
1765 }
1766
1767 /* Just set a flag if we found the matching entry */
1768 static int
1769 playlog_cb( Operation *op, SlapReply *rs )
1770 {
1771 if ( rs->sr_type == REP_SEARCH ) {
1772 op->o_callback->sc_private = (void *)1;
1773 }
1774 return rs->sr_err;
1775 }
1776
1777 /*
1778 * Check whether the last nmods UUIDs in the uuids list exist in the database
1779 * and (still) match the op filter, zero out the bv_len of any that still exist
1780 * and return the number of UUIDs we have confirmed are gone now.
1781 */
1782 static int
1783 check_uuidlist_presence(
1784 Operation *op,
1785 struct berval *uuids,
1786 int len,
1787 int nmods )
1788 {
1789 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1790 Operation fop = *op;
1791 SlapReply frs = { REP_RESULT };
1792 Filter mf, af;
1793 AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
1794 slap_callback cb = {0};
1795 int i, mods = nmods;
1796
1797 fop.o_sync_mode = 0;
1798 fop.o_callback = &cb;
1799 fop.ors_limit = NULL;
1800 fop.ors_tlimit = SLAP_NO_LIMIT;
1801 fop.ors_attrs = slap_anlist_all_attributes;
1802 fop.ors_attrsonly = 0;
1803 fop.o_managedsait = SLAP_CONTROL_CRITICAL;
1804
1805 af.f_choice = LDAP_FILTER_AND;
1806 af.f_next = NULL;
1807 af.f_and = &mf;
1808 mf.f_choice = LDAP_FILTER_EQUALITY;
1809 mf.f_ava = &eq;
1810 mf.f_av_desc = slap_schema.si_ad_entryUUID;
1811 mf.f_next = fop.ors_filter;
1812
1813 fop.ors_filter = &af;
1814
1815 cb.sc_response = playlog_cb;
1816
1817 fop.o_bd->bd_info = (BackendInfo *)on->on_info;
1818 for ( i=0; i<nmods; i++ ) {
1819 mf.f_av_value = uuids[ len - 1 - i ];
1820 cb.sc_private = NULL;
1821 fop.ors_slimit = 1;
1822
1823 if ( BER_BVISEMPTY( &mf.f_av_value ) ) {
1824 mods--;
1825 continue;
1826 }
1827
1828 rs_reinit( &frs, REP_RESULT );
1829 fop.o_bd->be_search( &fop, &frs );
1830 if ( cb.sc_private ) {
1831 uuids[ len - 1 - i ].bv_len = 0;
1832 mods--;
1833 }
1834 }
1835 fop.o_bd->bd_info = (BackendInfo *)on;
1836
1837 return mods;
1838 }
1839
1840 /*
1841 * On each entry we get from the DB:
1842 * - if it's an ADD, skip
1843 * - check we've not handled it yet, skip if we have
1844 * - check if it's a DELETE or missing from the DB now
1845 * - send a new syncinfo entry
1846 * - remember we've handled it already
1847 *
1848 * If we exhaust the list, clear it, forgetting entries we've handled so far.
1849 */
1850 static int
1851 syncprov_accesslog_uuid_cb( Operation *op, SlapReply *rs )
1852 {
1853 slap_callback *sc = op->o_callback;
1854 syncprov_accesslog_deletes *uuid_progress = sc->sc_private;
1855 Attribute *a, *attrs;
1856 sync_control *srs = uuid_progress->srs;
1857 struct berval *bv, csn[2] = {}, uuid[2] = {},
1858 add = BER_BVC("add"),
1859 delete = BER_BVC("delete"),
1860 modrdn = BER_BVC("modrdn");
1861 int cmp, sid, i, is_delete = 0, rc;
1862
1863 if ( rs->sr_type != REP_SEARCH ) {
1864 return rs->sr_err;
1865 }
1866 attrs = rs->sr_entry->e_attrs;
1867
1868 a = attr_find( attrs, ad_reqType );
1869 if ( !a || a->a_numvals == 0 ) {
1870 rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1871 return rs->sr_err;
1872 }
1873
1874 if ( bvmatch( &a->a_nvals[0], &add ) ) {
1875 return rs->sr_err;
1876 }
1877
1878 if ( bvmatch( &a->a_nvals[0], &delete ) ) {
1879 is_delete = 1;
1880 }
1881
1882 if ( bvmatch( &a->a_nvals[0], &modrdn ) ) {
1883 a = attr_find( attrs, ad_reqDN );
1884 if ( !a || a->a_numvals == 0 ) {
1885 rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1886 return rs->sr_err;
1887 }
1888
1889 /* Was it present in the first place? If not, skip: */
1890 if ( !dnIsSuffix( &a->a_nvals[0], &uuid_progress->op->o_req_ndn ) ) {
1891 return rs->sr_err;
1892 }
1893
1894 a = attr_find( attrs, ad_reqNewDN );
1895 if ( !a || a->a_numvals == 0 ) {
1896 rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1897 return rs->sr_err;
1898 }
1899
1900 /* Has it gone away? */
1901 if ( !dnIsSuffix( &a->a_nvals[0], &uuid_progress->op->o_req_ndn ) ) {
1902 is_delete = 1;
1903 }
1904 }
1905
1906 /*
1907 * Only pick entries that are both:
1908 */
1909 a = attr_find( attrs, slap_schema.si_ad_entryCSN );
1910 if ( !a || a->a_numvals == 0 ) {
1911 rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1912 return rs->sr_err;
1913 }
1914 csn[0] = a->a_nvals[0];
1915
1916 sid = slap_parse_csn_sid( &csn[0] );
1917
1918 /*
1919 * newer than cookieCSN (srs->sr_state.ctxcsn)
1920 */
1921 cmp = 1;
1922 for ( i=0; i<srs->sr_state.numcsns; i++ ) {
1923 if ( sid == srs->sr_state.sids[i] ) {
1924 cmp = ber_bvcmp( &csn[0], &srs->sr_state.ctxcsn[i] );
1925 break;
1926 }
1927 }
1928 if ( cmp <= 0 ) {
1929 Debug( LDAP_DEBUG_SYNC, "%s syncprov_accesslog_uuid_cb: "
1930 "cmp %d, csn %s too old\n",
1931 op->o_log_prefix, cmp, csn[0].bv_val );
1932 return rs->sr_err;
1933 }
1934
1935 /*
1936 * not newer than snapshot ctxcsn (uuid_progress->ctxcsn)
1937 */
1938 cmp = 0;
1939 for ( i=0; i<uuid_progress->numcsns; i++ ) {
1940 if ( sid == uuid_progress->sids[i] ) {
1941 cmp = ber_bvcmp( &csn[0], &uuid_progress->ctxcsn[i] );
1942 break;
1943 }
1944 }
1945 if ( cmp > 0 ) {
1946 Debug( LDAP_DEBUG_SYNC, "%s syncprov_accesslog_uuid_cb: "
1947 "cmp %d, csn %s too new\n",
1948 op->o_log_prefix, cmp, csn[0].bv_val );
1949 return rs->sr_err;
1950 }
1951
1952 a = attr_find( attrs, ad_reqEntryUUID );
1953 if ( !a || a->a_numvals == 0 ) {
1954 rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1955 return rs->sr_err;
1956 }
1957 uuid[0] = a->a_nvals[0];
1958
1959 bv = ldap_avl_find( uuid_progress->uuids, uuid, sp_uuid_cmp );
1960 if ( bv ) {
1961 /* Already checked or sent, no change */
1962 Debug( LDAP_DEBUG_SYNC, "%s syncprov_accesslog_uuid_cb: "
1963 "uuid %s already checked\n",
1964 op->o_log_prefix, a->a_vals[0].bv_val );
1965 return rs->sr_err;
1966 }
1967
1968 if ( !is_delete ) {
1969 is_delete = check_uuidlist_presence( uuid_progress->op, uuid, 1, 1 );
1970 }
1971 Debug( LDAP_DEBUG_SYNC, "%s syncprov_accesslog_uuid_cb: "
1972 "uuid %s is %s present\n",
1973 op->o_log_prefix, a->a_vals[0].bv_val,
1974 is_delete ? "no longer" : "still" );
1975
1976 i = uuid_progress->ndel++;
1977
1978 bv = &uuid_progress->uuid_list[i];
1979 bv->bv_val = &uuid_progress->uuid_buf[i*UUID_LEN];
1980 bv->bv_len = a->a_nvals[0].bv_len;
1981 AC_MEMCPY( bv->bv_val, a->a_nvals[0].bv_val, a->a_nvals[0].bv_len );
1982
1983 rc = ldap_avl_insert( &uuid_progress->uuids, bv, sp_uuid_cmp, ldap_avl_dup_error );
1984 assert( rc == LDAP_SUCCESS );
1985
1986 if ( is_delete ) {
1987 struct berval cookie;
1988
1989 slap_compose_sync_cookie( op, &cookie, srs->sr_state.ctxcsn,
1990 srs->sr_state.rid, slap_serverID ? slap_serverID : -1, csn );
1991 syncprov_sendinfo( uuid_progress->op, uuid_progress->rs,
1992 LDAP_TAG_SYNC_ID_SET, &cookie, 0, uuid, 1 );
1993 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
1994 }
1995
1996 if ( uuid_progress->ndel >= uuid_progress->list_len ) {
1997 int ndel;
1998
1999 assert( uuid_progress->ndel == uuid_progress->list_len );
2000 ndel = ldap_avl_free( uuid_progress->uuids, NULL );
2001 assert( ndel == uuid_progress->ndel );
2002 uuid_progress->uuids = NULL;
2003 uuid_progress->ndel = 0;
2004 }
2005
2006 return rs->sr_err;
2007 }
2008
2009 static int
2010 syncprov_play_sessionlog( Operation *op, SlapReply *rs, sync_control *srs,
2011 BerVarray ctxcsn, int numcsns, int *sids,
2012 struct berval *mincsn, int minsid )
2013 {
2014 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2015 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2016 sessionlog *sl = si->si_logs;
2017 int i, j, ndel, num, nmods, mmods, do_play = 0, rc = -1;
2018 BerVarray uuids, csns;
2019 struct berval uuid[2] = {}, csn[2] = {};
2020 slog_entry *se;
2021 TAvlnode *entry;
2022 char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
2023 struct berval delcsn[2];
2024
2025 ldap_pvt_thread_rdwr_wlock( &sl->sl_mutex );
2026 /* Are there any log entries, and is the consumer state
2027 * present in the session log?
2028 */
2029 if ( !sl->sl_num ) {
2030 ldap_pvt_thread_rdwr_wunlock( &sl->sl_mutex );
2031 return rc;
2032 }
2033 assert( sl->sl_num > 0 );
2034
2035 for ( i=0; i<sl->sl_numcsns; i++ ) {
2036 /* SID not present == new enough */
2037 if ( minsid < sl->sl_sids[i] ) {
2038 do_play = 1;
2039 break;
2040 }
2041 /* SID present */
2042 if ( minsid == sl->sl_sids[i] ) {
2043 /* new enough? */
2044 if ( ber_bvcmp( mincsn, &sl->sl_mincsn[i] ) >= 0 )
2045 do_play = 1;
2046 break;
2047 }
2048 }
2049 /* SID not present == new enough */
2050 if ( i == sl->sl_numcsns )
2051 do_play = 1;
2052
2053 if ( !do_play ) {
2054 ldap_pvt_thread_rdwr_wunlock( &sl->sl_mutex );
2055 return rc;
2056 }
2057
2058 num = sl->sl_num;
2059 i = 0;
2060 nmods = 0;
2061 sl->sl_playing++;
2062 ldap_pvt_thread_rdwr_wunlock( &sl->sl_mutex );
2063
2064 uuids = op->o_tmpalloc( (num) * sizeof( struct berval ) +
2065 num * UUID_LEN, op->o_tmpmemctx );
2066 uuids[0].bv_val = (char *)(uuids + num);
2067 csns = op->o_tmpalloc( (num) * sizeof( struct berval ) +
2068 num * LDAP_PVT_CSNSTR_BUFSIZE, op->o_tmpmemctx );
2069 csns[0].bv_val = (char *)(csns + num);
2070
2071 ldap_pvt_thread_rdwr_rlock( &sl->sl_mutex );
2072 /* Make a copy of the relevant UUIDs. Put the Deletes up front
2073 * and everything else at the end. Do this first so we can
2074 * let the write side manage the sessionlog again.
2075 */
2076 assert( sl->sl_entries );
2077
2078 /* Find first relevant log entry. If greater than mincsn, backtrack one entry */
2079 {
2080 slog_entry te = {0};
2081 te.se_csn = *mincsn;
2082 entry = ldap_tavl_find3( sl->sl_entries, &te, syncprov_sessionlog_cmp, &ndel );
2083 }
2084 if ( ndel > 0 && entry )
2085 entry = ldap_tavl_next( entry, TAVL_DIR_LEFT );
2086 /* if none, just start at beginning */
2087 if ( !entry )
2088 entry = ldap_tavl_end( sl->sl_entries, TAVL_DIR_LEFT );
2089
2090 do {
2091 char uuidstr[40] = {};
2092 slog_entry *se = entry->avl_data;
2093 int k;
2094
2095 /* Make sure writes can still make progress */
2096 ldap_pvt_thread_rdwr_runlock( &sl->sl_mutex );
2097 ndel = 1;
2098 for ( k=0; k<srs->sr_state.numcsns; k++ ) {
2099 if ( se->se_sid == srs->sr_state.sids[k] ) {
2100 ndel = ber_bvcmp( &se->se_csn, &srs->sr_state.ctxcsn[k] );
2101 break;
2102 }
2103 }
2104 if ( ndel <= 0 ) {
2105 ldap_pvt_thread_rdwr_rlock( &sl->sl_mutex );
2106 continue;
2107 }
2108 ndel = 0;
2109 for ( k=0; k<numcsns; k++ ) {
2110 if ( se->se_sid == sids[k] ) {
2111 ndel = ber_bvcmp( &se->se_csn, &ctxcsn[k] );
2112 break;
2113 }
2114 }
2115 if ( ndel > 0 ) {
2116 Debug( LDAP_DEBUG_SYNC, "%s syncprov_play_sessionlog: "
2117 "cmp %d, csn %s too new, we're finished\n",
2118 op->o_log_prefix, ndel, se->se_csn.bv_val );
2119 ldap_pvt_thread_rdwr_rlock( &sl->sl_mutex );
2120 break;
2121 }
2122 if ( se->se_tag == LDAP_REQ_DELETE ) {
2123 j = i;
2124 i++;
2125 } else {
2126 if ( se->se_tag == LDAP_REQ_ADD ) {
2127 ldap_pvt_thread_rdwr_rlock( &sl->sl_mutex );
2128 continue;
2129 }
2130 nmods++;
2131 j = num - nmods;
2132 }
2133 uuids[j].bv_val = uuids[0].bv_val + (j * UUID_LEN);
2134 AC_MEMCPY(uuids[j].bv_val, se->se_uuid.bv_val, UUID_LEN);
2135 uuids[j].bv_len = UUID_LEN;
2136
2137 csns[j].bv_val = csns[0].bv_val + (j * LDAP_PVT_CSNSTR_BUFSIZE);
2138 AC_MEMCPY(csns[j].bv_val, se->se_csn.bv_val, se->se_csn.bv_len);
2139 csns[j].bv_len = se->se_csn.bv_len;
2140 /* We're printing it */
2141 csns[j].bv_val[csns[j].bv_len] = '\0';
2142
2143 if ( LogTest( LDAP_DEBUG_SYNC ) ) {
2144 lutil_uuidstr_from_normalized( uuids[j].bv_val, uuids[j].bv_len,
2145 uuidstr, 40 );
2146 Debug( LDAP_DEBUG_SYNC, "%s syncprov_play_sessionlog: "
2147 "picking a %s entry uuid=%s cookie=%s\n",
2148 op->o_log_prefix, se->se_tag == LDAP_REQ_DELETE ? "deleted" : "modified",
2149 uuidstr, csns[j].bv_val );
2150 }
2151 ldap_pvt_thread_rdwr_rlock( &sl->sl_mutex );
2152 } while ( (entry = ldap_tavl_next( entry, TAVL_DIR_RIGHT )) != NULL );
2153 ldap_pvt_thread_rdwr_runlock( &sl->sl_mutex );
2154 ldap_pvt_thread_rdwr_wlock( &sl->sl_mutex );
2155 sl->sl_playing--;
2156 ldap_pvt_thread_rdwr_wunlock( &sl->sl_mutex );
2157
2158 ndel = i;
2159
2160 /* Zero out unused slots */
2161 for ( i=ndel; i < num - nmods; i++ )
2162 uuids[i].bv_len = 0;
2163
2164 /* Mods must be validated to see if they belong in this delete set.
2165 */
2166
2167 mmods = nmods;
2168 /* Strip any duplicates */
2169 for ( i=0; i<nmods; i++ ) {
2170 for ( j=0; j<ndel; j++ ) {
2171 if ( bvmatch( &uuids[j], &uuids[num - 1 - i] )) {
2172 uuids[num - 1 - i].bv_len = 0;
2173 mmods --;
2174 break;
2175 }
2176 }
2177 if ( uuids[num - 1 - i].bv_len == 0 ) continue;
2178 for ( j=0; j<i; j++ ) {
2179 if ( bvmatch( &uuids[num - 1 - j], &uuids[num - 1 - i] )) {
2180 uuids[num - 1 - i].bv_len = 0;
2181 mmods --;
2182 break;
2183 }
2184 }
2185 }
2186
2187 /* Check mods now */
2188 if ( mmods ) {
2189 check_uuidlist_presence( op, uuids, num, nmods );
2190 }
2191
2192 /* ITS#8768 Send entries sorted by CSN order */
2193 i = j = 0;
2194 while ( i < ndel || j < nmods ) {
2195 struct berval cookie;
2196 int index;
2197
2198 /* Skip over duplicate mods */
2199 if ( j < nmods && BER_BVISEMPTY( &uuids[ num - 1 - j ] ) ) {
2200 j++;
2201 continue;
2202 }
2203 index = num - 1 - j;
2204
2205 if ( i >= ndel ) {
2206 j++;
2207 } else if ( j >= nmods ) {
2208 index = i++;
2209 /* Take the oldest by CSN order */
2210 } else if ( ber_bvcmp( &csns[index], &csns[i] ) < 0 ) {
2211 j++;
2212 } else {
2213 index = i++;
2214 }
2215
2216 uuid[0] = uuids[index];
2217 csn[0] = csns[index];
2218
2219 slap_compose_sync_cookie( op, &cookie, srs->sr_state.ctxcsn,
2220 srs->sr_state.rid, slap_serverID ? slap_serverID : -1, csn );
2221 if ( LogTest( LDAP_DEBUG_SYNC ) ) {
2222 char uuidstr[40];
2223 lutil_uuidstr_from_normalized( uuid[0].bv_val, uuid[0].bv_len,
2224 uuidstr, 40 );
2225 Debug( LDAP_DEBUG_SYNC, "%s syncprov_play_sessionlog: "
2226 "sending a new disappearing entry uuid=%s cookie=%s\n",
2227 op->o_log_prefix, uuidstr, cookie.bv_val );
2228 }
2229
2230 /* TODO: we might batch those that share the same CSN (think present
2231 * phase), but would have to limit how many we send out at once */
2232 syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, &cookie, 0, uuid, 1 );
2233 }
2234 op->o_tmpfree( uuids, op->o_tmpmemctx );
2235 op->o_tmpfree( csns, op->o_tmpmemctx );
2236
2237 return LDAP_SUCCESS;
2238 }
2239
2240 static int
2241 syncprov_play_accesslog( Operation *op, SlapReply *rs, sync_control *srs,
2242 BerVarray ctxcsn, int numcsns, int *sids,
2243 struct berval *mincsn, int minsid )
2244 {
2245 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2246 syncprov_info_t *si = on->on_bi.bi_private;
2247 Operation fop;
2248 SlapReply frs = { REP_RESULT };
2249 slap_callback cb = {};
2250 Filter *f;
2251 syncprov_accesslog_deletes uuid_progress = {
2252 .op = op,
2253 .rs = rs,
2254 .srs = srs,
2255 .ctxcsn = ctxcsn,
2256 .numcsns = numcsns,
2257 .sids = sids,
2258 };
2259 struct berval oldestcsn = BER_BVNULL, newestcsn = BER_BVNULL,
2260 basedn, filterpattern = BER_BVC(
2261 "(&"
2262 "(entryCSN>=%s)"
2263 "(entryCSN<=%s)"
2264 "(reqResult=0)"
2265 "(|"
2266 "(reqDN:dnSubtreeMatch:=%s)"
2267 "(reqNewDN:dnSubtreeMatch:=%s)"
2268 ")"
2269 "(|"
2270 "(objectclass=auditWriteObject)"
2271 "(objectclass=auditExtended)"
2272 "))" );
2273 BackendDB *db;
2274 Entry *e;
2275 Attribute *a;
2276 int *minsids, i, j = 0, rc = -1;
2277
2278 assert( !BER_BVISNULL( &si->si_logbase ) );
2279
2280 db = select_backend( &si->si_logbase, 0 );
2281 if ( !db ) {
2282 Debug( LDAP_DEBUG_ANY, "%s syncprov_play_accesslog: "
2283 "No database configured to hold accesslog dn=%s\n",
2284 op->o_log_prefix, si->si_logbase.bv_val );
2285 return LDAP_NO_SUCH_OBJECT;
2286 }
2287
2288 fop = *op;
2289 fop.o_sync_mode = 0;
2290 fop.o_bd = db;
2291 rc = be_entry_get_rw( &fop, &si->si_logbase, NULL, ad_minCSN, 0, &e );
2292 if ( rc ) {
2293 return rc;
2294 }
2295
2296 a = attr_find( e->e_attrs, ad_minCSN );
2297 if ( !a ) {
2298 be_entry_release_rw( &fop, e, 0 );
2299 return LDAP_NO_SUCH_ATTRIBUTE;
2300 }
2301
2302 /*
2303 * If we got here:
2304 * - the consumer's cookie (srs->sr_state.ctxcsn) has the same sids in the
2305 * same order as ctxcsn
2306 * - at least one of the cookie's csns is older than its ctxcsn counterpart
2307 *
2308 * Now prepare the filter, we want it to be the union of all the intervals
2309 * between the cookie and our contextCSN for each sid. Right now, we can't
2310 * specify them separately, so just pick the boundary CSNs of non-empty
2311 * intervals as a conservative overestimate.
2312 *
2313 * Also check accesslog can actually serve this query based on what's
2314 * stored in minCSN.
2315 */
2316
2317 assert( srs->sr_state.numcsns == numcsns );
2318
2319 minsids = slap_parse_csn_sids( a->a_nvals, a->a_numvals, op->o_tmpmemctx );
2320 slap_sort_csn_sids( a->a_nvals, minsids, a->a_numvals, op->o_tmpmemctx );
2321 for ( i=0, j=0; i < numcsns; i++ ) {
2322 assert( srs->sr_state.sids[i] == sids[i] );
2323 if ( ber_bvcmp( &srs->sr_state.ctxcsn[i], &ctxcsn[i] ) >= 0 ) {
2324 /* Consumer is up to date for this sid */
2325 continue;
2326 }
2327 for ( ; j < a->a_numvals && minsids[j] < sids[i]; j++ )
2328 /* Find the right minCSN, if present */;
2329 if ( j == a->a_numvals || minsids[j] != sids[i] ||
2330 ber_bvcmp( &srs->sr_state.ctxcsn[i], &a->a_nvals[j] ) < 0 ) {
2331 /* Consumer is missing changes for a sid and minCSN indicates we
2332 * can't replay all relevant history */
2333 Debug( LDAP_DEBUG_SYNC, "%s syncprov_play_accesslog: "
2334 "accesslog information inadequate for log replay on csn=%s\n",
2335 op->o_log_prefix, srs->sr_state.ctxcsn[i].bv_val );
2336 slap_sl_free( minsids, op->o_tmpmemctx );
2337 be_entry_release_rw( &fop, e, 0 );
2338 return 1;
2339 }
2340 if ( BER_BVISEMPTY( &oldestcsn ) ||
2341 ber_bvcmp( &oldestcsn, &srs->sr_state.ctxcsn[i] ) > 0 ) {
2342 oldestcsn = srs->sr_state.ctxcsn[i];
2343 }
2344 if ( BER_BVISEMPTY( &newestcsn ) ||
2345 ber_bvcmp( &newestcsn, &ctxcsn[i] ) < 0 ) {
2346 newestcsn = ctxcsn[i];
2347 }
2348 }
2349 assert( !BER_BVISEMPTY( &oldestcsn ) && !BER_BVISEMPTY( &newestcsn ) &&
2350 ber_bvcmp( &oldestcsn, &newestcsn ) < 0 );
2351 slap_sl_free( minsids, op->o_tmpmemctx );
2352
2353 filter_escape_value_x( &op->o_req_ndn, &basedn, fop.o_tmpmemctx );
2354 /* filter_escape_value_x sets output to BVNULL if input value is empty,
2355 * supply our own copy */
2356 if ( BER_BVISEMPTY( &basedn ) ) {
2357 basedn.bv_val = "";
2358 }
2359 fop.o_req_ndn = fop.o_req_dn = si->si_logbase;
2360 fop.ors_filterstr.bv_val = fop.o_tmpalloc(
2361 filterpattern.bv_len +
2362 oldestcsn.bv_len + newestcsn.bv_len + 2 * basedn.bv_len,
2363 fop.o_tmpmemctx );
2364 fop.ors_filterstr.bv_len = sprintf( fop.ors_filterstr.bv_val,
2365 filterpattern.bv_val,
2366 oldestcsn.bv_val, newestcsn.bv_val, basedn.bv_val, basedn.bv_val );
2367 Debug( LDAP_DEBUG_SYNC, "%s syncprov_play_accesslog: "
2368 "prepared filter '%s', base='%s'\n",
2369 op->o_log_prefix, fop.ors_filterstr.bv_val, si->si_logbase.bv_val );
2370 f = str2filter_x( &fop, fop.ors_filterstr.bv_val );
2371 assert( f != NULL );
2372 fop.ors_filter = f;
2373
2374 if ( !BER_BVISEMPTY( &basedn ) ) {
2375 fop.o_tmpfree( basedn.bv_val, fop.o_tmpmemctx );
2376 }
2377 be_entry_release_rw( &fop, e, 0 );
2378
2379 /*
2380 * Allocate memory for list_len uuids for use by the callback, populate
2381 * with entries that we have sent or checked still match the filter.
2382 * A disappearing entry gets its uuid sent as a delete.
2383 *
2384 * in the callback, we need:
2385 * - original op and rs so we can send the message
2386 * - sync_control
2387 * - the uuid buffer and list and their length
2388 * - number of uuids we already have in the list
2389 * - the lookup structure so we don't have to check/send a uuid twice
2390 * (AVL?)
2391 */
2392 uuid_progress.list_len = SLAP_SYNCUUID_SET_SIZE;
2393 uuid_progress.uuid_list = fop.o_tmpalloc( (uuid_progress.list_len) * sizeof(struct berval), fop.o_tmpmemctx );
2394 uuid_progress.uuid_buf = fop.o_tmpalloc( (uuid_progress.list_len) * UUID_LEN, fop.o_tmpmemctx );
2395
2396 cb.sc_private = &uuid_progress;
2397 cb.sc_response = syncprov_accesslog_uuid_cb;
2398
2399 fop.o_callback = &cb;
2400
2401 rc = fop.o_bd->be_search( &fop, &frs );
2402
2403 ldap_avl_free( uuid_progress.uuids, NULL );
2404 fop.o_tmpfree( uuid_progress.uuid_buf, fop.o_tmpmemctx );
2405 fop.o_tmpfree( uuid_progress.uuid_list, fop.o_tmpmemctx );
2406 fop.o_tmpfree( fop.ors_filterstr.bv_val, fop.o_tmpmemctx );
2407 filter_free_x( &fop, f, 1 );
2408
2409 return rc;
2410 }
2411
2412 static int
2413 syncprov_new_ctxcsn( opcookie *opc, syncprov_info_t *si, int csn_changed, int numvals, BerVarray vals )
2414 {
2415 unsigned i;
2416 int j, sid;
2417
2418 for ( i=0; i<numvals; i++ ) {
2419 sid = slap_parse_csn_sid( &vals[i] );
2420 for ( j=0; j<si->si_numcsns; j++ ) {
2421 if ( sid < si->si_sids[j] )
2422 break;
2423 if ( sid == si->si_sids[j] ) {
2424 if ( ber_bvcmp( &vals[i], &si->si_ctxcsn[j] ) > 0 ) {
2425 ber_bvreplace( &si->si_ctxcsn[j], &vals[i] );
2426 csn_changed = 1;
2427 }
2428 break;
2429 }
2430 }
2431
2432 if ( j == si->si_numcsns || sid != si->si_sids[j] ) {
2433 slap_insert_csn_sids( (struct sync_cookie *)&si->si_ctxcsn,
2434 j, sid, &vals[i] );
2435 csn_changed = 1;
2436 }
2437 }
2438 if ( csn_changed )
2439 si->si_dirty = 0;
2440 ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
2441
2442 if ( csn_changed ) {
2443 syncops *ss;
2444 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
2445 for ( ss = si->si_ops; ss; ss = ss->s_next ) {
2446 if ( ss->s_op->o_abandon )
2447 continue;
2448 /* Send the updated csn to all syncrepl consumers,
2449 * including the server from which it originated.
2450 * The syncrepl consumer and syncprov provider on
2451 * the originating server may be configured to store
2452 * their csn values in different entries.
2453 */
2454 syncprov_qresp( opc, ss, LDAP_SYNC_NEW_COOKIE );
2455 }
2456 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
2457 }
2458 return csn_changed;
2459 }
2460
2461 static int
2462 syncprov_op_response( Operation *op, SlapReply *rs )
2463 {
2464 opcookie *opc = op->o_callback->sc_private;
2465 slap_overinst *on = opc->son;
2466 syncprov_info_t *si = on->on_bi.bi_private;
2467 syncmatches *sm;
2468
2469 if ( rs->sr_err == LDAP_SUCCESS )
2470 {
2471 struct berval maxcsn;
2472 char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
2473 int do_check = 0, have_psearches, foundit, csn_changed = 0;
2474
2475 ldap_pvt_thread_mutex_lock( &si->si_resp_mutex );
2476
2477 /* Update our context CSN */
2478 cbuf[0] = '\0';
2479 maxcsn.bv_val = cbuf;
2480 maxcsn.bv_len = sizeof(cbuf);
2481 ldap_pvt_thread_rdwr_wlock( &si->si_csn_rwlock );
2482
2483 slap_get_commit_csn( op, &maxcsn, &foundit );
2484 if ( BER_BVISEMPTY( &maxcsn ) && SLAP_GLUE_SUBORDINATE( op->o_bd )) {
2485 /* syncrepl queues the CSN values in the db where
2486 * it is configured , not where the changes are made.
2487 * So look for a value in the glue db if we didn't
2488 * find any in this db.
2489 */
2490 BackendDB *be = op->o_bd;
2491 op->o_bd = select_backend( &be->be_nsuffix[0], 1);
2492 maxcsn.bv_val = cbuf;
2493 maxcsn.bv_len = sizeof(cbuf);
2494 slap_get_commit_csn( op, &maxcsn, &foundit );
2495 op->o_bd = be;
2496 }
2497 if ( !BER_BVISEMPTY( &maxcsn ) ) {
2498 int i, sid;
2499 #ifdef CHECK_CSN
2500 Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
2501 assert( !syn->ssyn_validate( syn, &maxcsn ));
2502 #endif
2503 sid = slap_parse_csn_sid( &maxcsn );
2504 for ( i=0; i<si->si_numcsns; i++ ) {
2505 if ( sid < si->si_sids[i] )
2506 break;
2507 if ( sid == si->si_sids[i] ) {
2508 if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn[i] ) > 0 ) {
2509 ber_bvreplace( &si->si_ctxcsn[i], &maxcsn );
2510 csn_changed = 1;
2511 }
2512 break;
2513 }
2514 }
2515 /* It's a new SID for us */
2516 if ( i == si->si_numcsns || sid != si->si_sids[i] ) {
2517 slap_insert_csn_sids((struct sync_cookie *)&(si->si_ctxcsn),
2518 i, sid, &maxcsn );
2519 csn_changed = 1;
2520 }
2521 }
2522
2523 /* Don't do any processing for consumer contextCSN updates */
2524 if ( SLAPD_SYNC_IS_SYNCCONN( op->o_connid ) &&
2525 op->o_tag == LDAP_REQ_MODIFY &&
2526 op->orm_modlist &&
2527 op->orm_modlist->sml_op == LDAP_MOD_REPLACE &&
2528 op->orm_modlist->sml_desc == slap_schema.si_ad_contextCSN ) {
2529 /* Catch contextCSN updates from syncrepl. We have to look at
2530 * all the attribute values, as there may be more than one csn
2531 * that changed, and only one can be passed in the csn queue.
2532 */
2533 csn_changed = syncprov_new_ctxcsn( opc, si, csn_changed,
2534 op->orm_modlist->sml_numvals, op->orm_modlist->sml_values );
2535 if ( csn_changed )
2536 si->si_numops++;
2537 goto leave;
2538 }
2539 if ( op->o_dont_replicate ) {
2540 if ( csn_changed )
2541 si->si_numops++;
2542 ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
2543 goto leave;
2544 }
2545
2546 /* If we're adding the context entry, parse all of its contextCSNs */
2547 if ( op->o_tag == LDAP_REQ_ADD &&
2548 dn_match( &op->o_req_ndn, &si->si_contextdn )) {
2549 Attribute *a = attr_find( op->ora_e->e_attrs, slap_schema.si_ad_contextCSN );
2550 if ( a ) {
2551 csn_changed = syncprov_new_ctxcsn( opc, si, csn_changed, a->a_numvals, a->a_vals );
2552 if ( csn_changed )
2553 si->si_numops++;
2554 goto added;
2555 }
2556 }
2557
2558 if ( csn_changed )
2559 si->si_numops++;
2560 if ( si->si_chkops || si->si_chktime ) {
2561 /* Never checkpoint adding the context entry,
2562 * it will deadlock
2563 */
2564 if ( op->o_tag != LDAP_REQ_ADD ||
2565 !dn_match( &op->o_req_ndn, &si->si_contextdn )) {
2566 if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
2567 do_check = 1;
2568 si->si_numops = 0;
2569 }
2570 if ( si->si_chktime &&
2571 (op->o_time - si->si_chklast >= si->si_chktime )) {
2572 if ( si->si_chklast ) {
2573 do_check = 1;
2574 si->si_chklast = op->o_time;
2575 } else {
2576 si->si_chklast = 1;
2577 }
2578 }
2579 }
2580 }
2581 si->si_dirty = !csn_changed;
2582 ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
2583
2584 added:
2585 if ( do_check ) {
2586 ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2587 syncprov_checkpoint( op, on );
2588 ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2589 }
2590
2591 /* only update consumer ctx if this is a newer csn */
2592 if ( csn_changed ) {
2593 opc->sctxcsn = maxcsn;
2594 }
2595
2596 /* Handle any persistent searches */
2597 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
2598 have_psearches = ( si->si_ops != NULL );
2599 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
2600 if ( have_psearches ) {
2601 syncprov_matchops( op, opc, 0 );
2602 }
2603
2604 /* Add any log records */
2605 if ( si->si_logs ) {
2606 syncprov_add_slog( op );
2607 }
2608 leave: ldap_pvt_thread_mutex_unlock( &si->si_resp_mutex );
2609 }
2610 return SLAP_CB_CONTINUE;
2611 }
2612
2613 /* We don't use a subentry to store the context CSN any more.
2614 * We expose the current context CSN as an operational attribute
2615 * of the suffix entry.
2616 */
2617 static int
2618 syncprov_op_compare( Operation *op, SlapReply *rs )
2619 {
2620 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2621 syncprov_info_t *si = on->on_bi.bi_private;
2622 int rc = SLAP_CB_CONTINUE;
2623
2624 if ( dn_match( &op->o_req_ndn, &si->si_contextdn ) &&
2625 op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
2626 {
2627 Entry e = {0};
2628 Attribute a = {0};
2629
2630 e.e_name = si->si_contextdn;
2631 e.e_nname = si->si_contextdn;
2632 e.e_attrs = &a;
2633
2634 a.a_desc = slap_schema.si_ad_contextCSN;
2635
2636 ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
2637
2638 a.a_vals = si->si_ctxcsn;
2639 a.a_nvals = a.a_vals;
2640 a.a_numvals = si->si_numcsns;
2641
2642 rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
2643 &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
2644 if ( ! rs->sr_err ) {
2645 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
2646 goto return_results;
2647 }
2648
2649 if ( get_assert( op ) &&
2650 ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
2651 {
2652 rs->sr_err = LDAP_ASSERTION_FAILED;
2653 goto return_results;
2654 }
2655
2656
2657 rs->sr_err = LDAP_COMPARE_FALSE;
2658
2659 if ( attr_valfind( &a,
2660 SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
2661 SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
2662 &op->oq_compare.rs_ava->aa_value, NULL, op->o_tmpmemctx ) == 0 )
2663 {
2664 rs->sr_err = LDAP_COMPARE_TRUE;
2665 }
2666
2667 return_results:;
2668
2669 ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
2670
2671 send_ldap_result( op, rs );
2672
2673 if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
2674 rs->sr_err = LDAP_SUCCESS;
2675 }
2676 rc = rs->sr_err;
2677 }
2678
2679 return rc;
2680 }
2681
2682 static int
2683 syncprov_op_mod( Operation *op, SlapReply *rs )
2684 {
2685 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
2686 syncprov_info_t *si = on->on_bi.bi_private;
2687 slap_callback *cb;
2688 opcookie *opc;
2689 int have_psearches, cbsize;
2690
2691 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
2692 have_psearches = ( si->si_ops != NULL );
2693 si->si_active++;
2694 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
2695
2696 cbsize = sizeof(slap_callback) + sizeof(opcookie) +
2697 (have_psearches ? sizeof(modinst) : 0 );
2698
2699 cb = op->o_tmpcalloc(1, cbsize, op->o_tmpmemctx);
2700 opc = (opcookie *)(cb+1);
2701 opc->son = on;
2702 cb->sc_response = syncprov_op_response;
2703 cb->sc_cleanup = syncprov_op_cleanup;
2704 cb->sc_private = opc;
2705 cb->sc_next = op->o_callback;
2706 op->o_callback = cb;
2707
2708 opc->osid = -1;
2709 opc->rsid = -1;
2710 if ( op->o_csn.bv_val ) {
2711 opc->osid = slap_parse_csn_sid( &op->o_csn );
2712 }
2713 if ( op->o_controls ) {
2714 struct sync_cookie *scook =
2715 op->o_controls[slap_cids.sc_LDAPsync];
2716 if ( scook )
2717 opc->rsid = scook->sid;
2718 }
2719
2720 if ( op->o_dont_replicate )
2721 return SLAP_CB_CONTINUE;
2722
2723 /* If there are active persistent searches, lock this operation.
2724 * See seqmod.c for the locking logic on its own.
2725 */
2726 if ( have_psearches ) {
2727 modtarget *mt, mtdummy;
2728 modinst *mi;
2729
2730 mi = (modinst *)(opc+1);
2731 mi->mi_op = op;
2732
2733 /* See if we're already modifying this entry... */
2734 mtdummy.mt_dn = op->o_req_ndn;
2735 retry:
2736 ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
2737 mt = ldap_avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
2738 if ( mt ) {
2739 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
2740 if ( mt->mt_mods == NULL ) {
2741 /* Cannot reuse this mt, as another thread is about
2742 * to release it in syncprov_op_cleanup. Wait for them
2743 * to finish; our own insert is required to succeed.
2744 */
2745 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
2746 ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
2747 ldap_pvt_thread_yield();
2748 goto retry;
2749 }
2750 }
2751 if ( mt ) {
2752 mt->mt_tail->mi_next = mi;
2753 mt->mt_tail = mi;
2754 ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
2755 /* wait for this op to get to head of list */
2756 while ( mt->mt_mods != mi ) {
2757 modinst *m2;
2758 /* don't wait on other mods from the same thread */
2759 for ( m2 = mt->mt_mods; m2; m2 = m2->mi_next ) {
2760 if ( m2->mi_op->o_threadctx == op->o_threadctx ) {
2761 break;
2762 }
2763 }
2764 if ( m2 )
2765 break;
2766
2767 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
2768 /* FIXME: if dynamic config can delete overlays or
2769 * databases we'll have to check for cleanup here.
2770 * Currently it's not an issue because there are
2771 * no dynamic config deletes...
2772 */
2773 if ( slapd_shutdown )
2774 return SLAPD_ABANDON;
2775
2776 if ( !ldap_pvt_thread_pool_pausewait( &connection_pool ))
2777 ldap_pvt_thread_yield();
2778 ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
2779
2780 /* clean up if the caller is giving up */
2781 if ( op->o_abandon ) {
2782 modinst **m2;
2783 slap_callback **sc;
2784 for (m2 = &mt->mt_mods; ; m2 = &(*m2)->mi_next) {
2785 if ( *m2 == mi ) {
2786 *m2 = mi->mi_next;
2787 if ( mt->mt_tail == mi )
2788 mt->mt_tail = ( m2 == &mt->mt_mods ) ? NULL : (modinst *)m2;
2789 break;
2790 }
2791 }
2792 for (sc = &op->o_callback; ; sc = &(*sc)->sc_next) {
2793 if ( *sc == cb ) {
2794 *sc = cb->sc_next;
2795 break;
2796 }
2797 }
2798 op->o_tmpfree( cb, op->o_tmpmemctx );
2799 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
2800 return SLAPD_ABANDON;
2801 }
2802 }
2803 ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
2804 } else {
2805 /* Record that we're modifying this entry now */
2806 mt = ch_malloc( sizeof(modtarget) );
2807 mt->mt_mods = mi;
2808 mt->mt_tail = mi;
2809 ber_dupbv( &mt->mt_dn, &mi->mi_op->o_req_ndn );
2810 ldap_pvt_thread_mutex_init( &mt->mt_mutex );
2811 ldap_avl_insert( &si->si_mods, mt, sp_avl_cmp, ldap_avl_dup_error );
2812 ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
2813 }
2814 opc->smt = mt;
2815 }
2816
2817 if (( have_psearches || si->si_logs ) && op->o_tag != LDAP_REQ_ADD )
2818 syncprov_matchops( op, opc, 1 );
2819
2820 return SLAP_CB_CONTINUE;
2821 }
2822
2823 static int
2824 syncprov_op_extended( Operation *op, SlapReply *rs )
2825 {
2826 if ( exop_is_write( op ))
2827 return syncprov_op_mod( op, rs );
2828
2829 return SLAP_CB_CONTINUE;
2830 }
2831
2832 typedef struct searchstate {
2833 slap_overinst *ss_on;
2834 syncops *ss_so;
2835 BerVarray ss_ctxcsn;
2836 int *ss_sids;
2837 int ss_numcsns;
2838 #define SS_PRESENT 0x01
2839 #define SS_CHANGED 0x02
2840 int ss_flags;
2841 } searchstate;
2842
2843 typedef struct SyncOperationBuffer {
2844 Operation sob_op;
2845 Opheader sob_hdr;
2846 OpExtra sob_oe;
2847 AttributeName sob_extra; /* not always present */
2848 /* Further data allocated here */
2849 } SyncOperationBuffer;
2850
2851 static void
2852 syncprov_detach_op( Operation *op, syncops *so, slap_overinst *on )
2853 {
2854 SyncOperationBuffer *sopbuf2;
2855 Operation *op2;
2856 int i, alen = 0;
2857 size_t size;
2858 char *ptr;
2859 GroupAssertion *g1, *g2;
2860
2861 /* count the search attrs */
2862 for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2863 alen += op->ors_attrs[i].an_name.bv_len + 1;
2864 }
2865 /* Make a new copy of the operation */
2866 size = offsetof( SyncOperationBuffer, sob_extra ) +
2867 (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
2868 op->o_req_dn.bv_len + 1 +
2869 op->o_req_ndn.bv_len + 1 +
2870 op->o_ndn.bv_len + 1 +
2871 so->s_filterstr.bv_len + 1;
2872 sopbuf2 = ch_calloc( 1, size );
2873 op2 = &sopbuf2->sob_op;
2874 op2->o_hdr = &sopbuf2->sob_hdr;
2875 LDAP_SLIST_FIRST(&op2->o_extra) = &sopbuf2->sob_oe;
2876
2877 /* Copy the fields we care about explicitly, leave the rest alone */
2878 *op2->o_hdr = *op->o_hdr;
2879 op2->o_tag = op->o_tag;
2880 op2->o_time = op->o_time;
2881 op2->o_bd = on->on_info->oi_origdb;
2882 op2->o_request = op->o_request;
2883 op2->o_managedsait = op->o_managedsait;
2884 LDAP_SLIST_FIRST(&op2->o_extra)->oe_key = on;
2885 LDAP_SLIST_NEXT(LDAP_SLIST_FIRST(&op2->o_extra), oe_next) = NULL;
2886
2887 ptr = (char *) sopbuf2 + offsetof( SyncOperationBuffer, sob_extra );
2888 if ( i ) {
2889 op2->ors_attrs = (AttributeName *) ptr;
2890 ptr = (char *) &op2->ors_attrs[i+1];
2891 for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
2892 op2->ors_attrs[i] = op->ors_attrs[i];
2893 op2->ors_attrs[i].an_name.bv_val = ptr;
2894 ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
2895 }
2896 BER_BVZERO( &op2->ors_attrs[i].an_name );
2897 }
2898
2899 op2->o_authz = op->o_authz;
2900 op2->o_ndn.bv_val = ptr;
2901 ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
2902 op2->o_dn = op2->o_ndn;
2903 op2->o_req_dn.bv_len = op->o_req_dn.bv_len;
2904 op2->o_req_dn.bv_val = ptr;
2905 ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
2906 op2->o_req_ndn.bv_len = op->o_req_ndn.bv_len;
2907 op2->o_req_ndn.bv_val = ptr;
2908 ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
2909 op2->ors_filterstr.bv_val = ptr;
2910 strcpy( ptr, so->s_filterstr.bv_val );
2911 op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
2912
2913 /* Skip the AND/GE clause that we stuck on in front */
2914 if ( so->s_flags & PS_FIX_FILTER ) {
2915 op2->ors_filter = op->ors_filter->f_and->f_next;
2916 so->s_flags ^= PS_FIX_FILTER;
2917 } else {
2918 op2->ors_filter = op->ors_filter;
2919 }
2920 op2->ors_filter = filter_dup( op2->ors_filter, NULL );
2921 so->s_op = op2;
2922
2923 /* Copy any cached group ACLs individually */
2924 op2->o_groups = NULL;
2925 for ( g1=op->o_groups; g1; g1=g1->ga_next ) {
2926 g2 = ch_malloc( sizeof(GroupAssertion) + g1->ga_len );
2927 *g2 = *g1;
2928 strcpy( g2->ga_ndn, g1->ga_ndn );
2929 g2->ga_next = op2->o_groups;
2930 op2->o_groups = g2;
2931 }
2932 /* Don't allow any further group caching */
2933 op2->o_do_not_cache = 1;
2934
2935 /* Add op2 to conn so abandon will find us */
2936 op->o_conn->c_n_ops_executing++;
2937 op->o_conn->c_n_ops_completed--;
2938 LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op2, o_next );
2939 so->s_flags |= PS_IS_DETACHED;
2940 }
2941
2942 static int
2943 syncprov_search_response( Operation *op, SlapReply *rs )
2944 {
2945 searchstate *ss = op->o_callback->sc_private;
2946 slap_overinst *on = ss->ss_on;
2947 syncops *so = ss->ss_so;
2948 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
2949 sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
2950
2951 if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
2952 Attribute *a;
2953 /* If we got a referral without a referral object, there's
2954 * something missing that we cannot replicate. Just ignore it.
2955 * The consumer will abort because we didn't send the expected
2956 * control.
2957 */
2958 if ( !rs->sr_entry ) {
2959 assert( rs->sr_entry != NULL );
2960 Debug( LDAP_DEBUG_ANY, "%s syncprov_search_response: "
2961 "bogus referral in context\n", op->o_log_prefix );
2962 return SLAP_CB_CONTINUE;
2963 }
2964 if ( is_entry_glue( rs->sr_entry ) ) {
2965 return LDAP_SUCCESS;
2966 }
2967 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryCSN );
2968 if ( a == NULL && rs->sr_operational_attrs != NULL ) {
2969 a = attr_find( rs->sr_operational_attrs, slap_schema.si_ad_entryCSN );
2970 }
2971 if ( a ) {
2972 int i, sid;
2973 sid = slap_parse_csn_sid( &a->a_nvals[0] );
2974
2975 /* If not a persistent search */
2976 if ( !so ) {
2977 /* Make sure entry is less than the snapshot'd contextCSN */
2978 for ( i=0; i<ss->ss_numcsns; i++ ) {
2979 if ( sid == ss->ss_sids[i] && ber_bvcmp( &a->a_nvals[0],
2980 &ss->ss_ctxcsn[i] ) > 0 ) {
2981 Debug( LDAP_DEBUG_SYNC, "%s syncprov_search_response: "
2982 "Entry %s CSN %s greater than snapshot %s\n",
2983 op->o_log_prefix,
2984 rs->sr_entry->e_name.bv_val,
2985 a->a_nvals[0].bv_val,
2986 ss->ss_ctxcsn[i].bv_val );
2987 return LDAP_SUCCESS;
2988 }
2989 }
2990 }
2991
2992 /* Don't send old entries twice */
2993 if ( srs->sr_state.ctxcsn ) {
2994 for ( i=0; i<srs->sr_state.numcsns; i++ ) {
2995 if ( sid == srs->sr_state.sids[i] &&
2996 ber_bvcmp( &a->a_nvals[0],
2997 &srs->sr_state.ctxcsn[i] )<= 0 ) {
2998 Debug( LDAP_DEBUG_SYNC, "%s syncprov_search_response: "
2999 "Entry %s CSN %s older or equal to ctx %s\n",
3000 op->o_log_prefix,
3001 rs->sr_entry->e_name.bv_val,
3002 a->a_nvals[0].bv_val,
3003 srs->sr_state.ctxcsn[i].bv_val );
3004 return LDAP_SUCCESS;
3005 }
3006 }
3007 }
3008 }
3009 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
3010 op->o_tmpmemctx );
3011 rs->sr_ctrls[1] = NULL;
3012 rs->sr_flags |= REP_CTRLS_MUSTBEFREED;
3013 /* If we're in delta-sync mode, always send a cookie */
3014 if ( si->si_nopres && si->si_usehint && a ) {
3015 struct berval cookie;
3016 slap_compose_sync_cookie( op, &cookie, a->a_nvals, srs->sr_state.rid,
3017 slap_serverID ? slap_serverID : -1, NULL );
3018 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
3019 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 1, &cookie );
3020 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
3021 } else {
3022 rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
3023 LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
3024 }
3025 } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
3026 struct berval cookie = BER_BVNULL;
3027
3028 if ( ( ss->ss_flags & SS_CHANGED ) &&
3029 ss->ss_ctxcsn && !BER_BVISNULL( &ss->ss_ctxcsn[0] )) {
3030 slap_compose_sync_cookie( op, &cookie, ss->ss_ctxcsn,
3031 srs->sr_state.rid,
3032 slap_serverID ? slap_serverID : -1, NULL );
3033
3034 Debug( LDAP_DEBUG_SYNC, "%s syncprov_search_response: cookie=%s\n",
3035 op->o_log_prefix, cookie.bv_val );
3036 }
3037
3038 /* Is this a regular refresh?
3039 * Note: refresh never gets here if there were no changes
3040 */
3041 if ( !so ) {
3042 rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
3043 op->o_tmpmemctx );
3044 rs->sr_ctrls[1] = NULL;
3045 rs->sr_flags |= REP_CTRLS_MUSTBEFREED;
3046 rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
3047 0, 1, &cookie, ( ss->ss_flags & SS_PRESENT ) ? LDAP_SYNC_REFRESH_PRESENTS :
3048 LDAP_SYNC_REFRESH_DELETES );
3049 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
3050 } else {
3051 /* It's RefreshAndPersist, transition to Persist phase */
3052 rs->sr_err = SLAPD_NO_REPLY;
3053 syncprov_sendinfo( op, rs, ( ss->ss_flags & SS_PRESENT ) ?
3054 LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
3055 ( ss->ss_flags & SS_CHANGED ) ? &cookie : NULL,
3056 1, NULL, 0 );
3057 if ( !BER_BVISNULL( &cookie ))
3058 op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
3059
3060 /* Detach this Op from frontend control */
3061 ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
3062
3063 /* But not if this connection was closed along the way */
3064 if ( op->o_abandon ) {
3065 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
3066 /* syncprov_ab_cleanup will free this syncop */
3067 return SLAPD_ABANDON;
3068
3069 } else {
3070 ldap_pvt_thread_mutex_lock( &so->s_mutex );
3071 /* Turn off the refreshing flag */
3072 so->s_flags ^= PS_IS_REFRESHING;
3073
3074 Debug( LDAP_DEBUG_SYNC, "%s syncprov_search_response: "
3075 "detaching op\n", op->o_log_prefix );
3076 syncprov_detach_op( op, so, on );
3077
3078 ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
3079
3080 /* If there are queued responses, fire them off */
3081 if ( so->s_res )
3082 syncprov_qstart( so );
3083 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
3084 return rs->sr_err;
3085 }
3086 }
3087 }
3088
3089 return SLAP_CB_CONTINUE;
3090 }
3091
3092 static int
3093 syncprov_search_cb( Operation *op, SlapReply *rs )
3094 {
3095 /*
3096 * Prevent the glue overlay from processing subordinates when it is
3097 * configured (explicitly or implicitly) below the syncprov overlay.
3098 */
3099 if ( rs->sr_type == REP_RESULT )
3100 op->o_no_subordinate_glue = 1;
3101 return SLAP_CB_CONTINUE;
3102 }
3103
3104 static int
3105 syncprov_search_cleanup( Operation *op, SlapReply *rs )
3106 {
3107 if ( rs->sr_type == REP_RESULT || rs->sr_type == REP_INTERMEDIATE ||
3108 rs->sr_err == SLAPD_ABANDON || op->o_abandon ) {
3109 searchstate *ss = op->o_callback->sc_private;
3110 if ( ss && ss->ss_numcsns ) {
3111 ber_bvarray_free_x( ss->ss_ctxcsn, op->o_tmpmemctx );
3112 op->o_tmpfree( ss->ss_sids, op->o_tmpmemctx );
3113 }
3114 slap_freeself_cb( op, rs );
3115 }
3116 return SLAP_CB_CONTINUE;
3117 }
3118
3119 static int
3120 syncprov_op_search( Operation *op, SlapReply *rs )
3121 {
3122 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3123 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
3124 slap_callback *cb;
3125 int gotstate = 0, changed = 0, do_present = 0;
3126 syncops *sop = NULL;
3127 searchstate *ss;
3128 sync_control *srs;
3129 BerVarray ctxcsn;
3130 int i, *sids, numcsns;
3131 struct berval mincsn, maxcsn;
3132 int minsid, maxsid;
3133 int dirty = 0;
3134
3135 if ( op->o_sync > SLAP_CONTROL_IGNORED ) {
3136 cb = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
3137 cb->sc_response = syncprov_search_cb;
3138 cb->sc_cleanup = syncprov_search_cleanup;
3139 cb->sc_next = op->o_callback;
3140 op->o_callback = cb;
3141 }
3142
3143 if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
3144
3145 if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
3146 send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
3147 return rs->sr_err;
3148 }
3149
3150 srs = op->o_controls[slap_cids.sc_LDAPsync];
3151 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3152 "got a %ssearch with a cookie=%s\n",
3153 op->o_log_prefix,
3154 op->o_sync_mode & SLAP_SYNC_PERSIST ? "persistent ": "",
3155 srs->sr_state.octet_str.bv_val );
3156
3157 /* If this is a persistent search, set it up right away */
3158 if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
3159 syncops so = {0};
3160 fbase_cookie fc;
3161 opcookie opc;
3162 slap_callback sc = {0};
3163
3164 fc.fss = &so;
3165 fc.fbase = 0;
3166 so.s_eid = NOID;
3167 so.s_op = op;
3168 so.s_flags = PS_IS_REFRESHING | PS_FIND_BASE;
3169 /* syncprov_findbase expects to be called as a callback... */
3170 sc.sc_private = &opc;
3171 opc.son = on;
3172 ldap_pvt_thread_mutex_init( &so.s_mutex );
3173 cb = op->o_callback;
3174 op->o_callback = &sc;
3175 rs->sr_err = syncprov_findbase( op, &fc );
3176 op->o_callback = cb;
3177 ldap_pvt_thread_mutex_destroy( &so.s_mutex );
3178
3179 /* Special case, if client knows nothing, nor do we, keep going */
3180 if ( srs->sr_state.numcsns == 0 && rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
3181 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3182 "both our DB and client empty, ignoring NO_SUCH_OBJECT\n",
3183 op->o_log_prefix );
3184 rs->sr_err = LDAP_SUCCESS;
3185 }
3186
3187 if ( rs->sr_err != LDAP_SUCCESS ) {
3188 send_ldap_result( op, rs );
3189 return rs->sr_err;
3190 }
3191 sop = ch_malloc( sizeof( syncops ));
3192 *sop = so;
3193 sop->s_rid = srs->sr_state.rid;
3194 sop->s_sid = srs->sr_state.sid;
3195 /* set refcount=2 to prevent being freed out from under us
3196 * by abandons that occur while we're running here
3197 */
3198 sop->s_inuse = 2;
3199
3200 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
3201 while ( si->si_active ) {
3202 /* Wait for active mods to finish before proceeding, as they
3203 * may already have inspected the si_ops list looking for
3204 * consumers to replicate the change to. Using the log
3205 * doesn't help, as we may finish playing it before the
3206 * active mods gets added to it.
3207 */
3208 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
3209 if ( slapd_shutdown ) {
3210 aband:
3211 ch_free( sop->s_base.bv_val );
3212 ch_free( sop );
3213 return SLAPD_ABANDON;
3214 }
3215 if ( !ldap_pvt_thread_pool_pausewait( &connection_pool ))
3216 ldap_pvt_thread_yield();
3217 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
3218 }
3219 if ( op->o_abandon ) {
3220 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
3221 goto aband;
3222 }
3223 ldap_pvt_thread_mutex_init( &sop->s_mutex );
3224 sop->s_next = si->si_ops;
3225 sop->s_si = si;
3226 si->si_ops = sop;
3227 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
3228 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3229 "registered persistent search\n", op->o_log_prefix );
3230 }
3231
3232 /* snapshot the ctxcsn
3233 * Note: this must not be done before the psearch setup. (ITS#8365)
3234 */
3235 ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
3236 numcsns = si->si_numcsns;
3237 if ( numcsns ) {
3238 ber_bvarray_dup_x( &ctxcsn, si->si_ctxcsn, op->o_tmpmemctx );
3239 sids = op->o_tmpalloc( numcsns * sizeof(int), op->o_tmpmemctx );
3240 for ( i=0; i<numcsns; i++ )
3241 sids[i] = si->si_sids[i];
3242 } else {
3243 ctxcsn = NULL;
3244 sids = NULL;
3245 }
3246 dirty = si->si_dirty;
3247 ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
3248
3249 /* If we have a cookie, handle the PRESENT lookups */
3250 if ( srs->sr_state.ctxcsn ) {
3251 sessionlog *sl;
3252 int i, j;
3253
3254 /* If we don't have any CSN of our own yet, bail out.
3255 */
3256 if ( !numcsns ) {
3257 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3258 rs->sr_text = "consumer has state info but provider doesn't!";
3259 goto bailout;
3260 }
3261
3262 if ( !si->si_nopres )
3263 do_present = SS_PRESENT;
3264
3265 /* If there are SIDs we don't recognize in the cookie, drop them */
3266 for (i=0; i<srs->sr_state.numcsns; ) {
3267 for (j=i; j<numcsns; j++) {
3268 if ( srs->sr_state.sids[i] <= sids[j] ) {
3269 break;
3270 }
3271 }
3272 /* not found */
3273 if ( j == numcsns || srs->sr_state.sids[i] != sids[j] ) {
3274 char *tmp = srs->sr_state.ctxcsn[i].bv_val;
3275 srs->sr_state.numcsns--;
3276 for ( j=i; j<srs->sr_state.numcsns; j++ ) {
3277 srs->sr_state.ctxcsn[j] = srs->sr_state.ctxcsn[j+1];
3278 srs->sr_state.sids[j] = srs->sr_state.sids[j+1];
3279 }
3280 srs->sr_state.ctxcsn[j].bv_val = tmp;
3281 srs->sr_state.ctxcsn[j].bv_len = 0;
3282 continue;
3283 }
3284 i++;
3285 }
3286
3287 if (srs->sr_state.numcsns != numcsns) {
3288 /* consumer doesn't have the right number of CSNs */
3289 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3290 "consumer cookie is missing a csn we track\n",
3291 op->o_log_prefix );
3292
3293 changed = SS_CHANGED;
3294 if ( srs->sr_state.ctxcsn ) {
3295 ber_bvarray_free_x( srs->sr_state.ctxcsn, op->o_tmpmemctx );
3296 srs->sr_state.ctxcsn = NULL;
3297 }
3298 if ( srs->sr_state.sids ) {
3299 slap_sl_free( srs->sr_state.sids, op->o_tmpmemctx );
3300 srs->sr_state.sids = NULL;
3301 }
3302 srs->sr_state.numcsns = 0;
3303 goto shortcut;
3304 }
3305
3306 /* Find the smallest CSN which differs from contextCSN */
3307 mincsn.bv_len = 0;
3308 maxcsn.bv_len = 0;
3309 for ( i=0,j=0; i<srs->sr_state.numcsns; i++ ) {
3310 int newer;
3311 while ( srs->sr_state.sids[i] != sids[j] ) j++;
3312 if ( BER_BVISEMPTY( &maxcsn ) || ber_bvcmp( &maxcsn,
3313 &srs->sr_state.ctxcsn[i] ) < 0 ) {
3314 maxcsn = srs->sr_state.ctxcsn[i];
3315 maxsid = sids[j];
3316 }
3317 newer = ber_bvcmp( &srs->sr_state.ctxcsn[i], &ctxcsn[j] );
3318 /* If our state is newer, tell consumer about changes */
3319 if ( newer < 0) {
3320 changed = SS_CHANGED;
3321 if ( BER_BVISEMPTY( &mincsn ) || ber_bvcmp( &mincsn,
3322 &srs->sr_state.ctxcsn[i] ) > 0 ) {
3323 mincsn = srs->sr_state.ctxcsn[i];
3324 minsid = sids[j];
3325 }
3326 } else if ( newer > 0 && sids[j] == slap_serverID ) {
3327 /* our state is older, complain to consumer */
3328 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
3329 rs->sr_text = "consumer state is newer than provider!";
3330 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3331 "consumer %d state %s is newer than provider %d state %s\n",
3332 op->o_log_prefix, sids[i], srs->sr_state.ctxcsn[i].bv_val,
3333 sids[j], /* == slap_serverID */
3334 ctxcsn[j].bv_val);
3335 bailout:
3336 if ( sop ) {
3337 syncops **sp = &si->si_ops;
3338
3339 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
3340 while ( *sp != sop )
3341 sp = &(*sp)->s_next;
3342 *sp = sop->s_next;
3343 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
3344 ch_free( sop->s_base.bv_val );
3345 ch_free( sop );
3346 }
3347 rs->sr_ctrls = NULL;
3348 send_ldap_result( op, rs );
3349 if ( numcsns ) {
3350 ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
3351 op->o_tmpfree( sids, op->o_tmpmemctx );
3352 }
3353 return rs->sr_err;
3354 }
3355 }
3356 if ( BER_BVISEMPTY( &mincsn )) {
3357 mincsn = maxcsn;
3358 minsid = maxsid;
3359 }
3360
3361 /* If nothing has changed, shortcut it */
3362 if ( !changed && !dirty ) {
3363 do_present = 0;
3364 no_change: if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
3365 LDAPControl *ctrls[2];
3366
3367 ctrls[0] = NULL;
3368 ctrls[1] = NULL;
3369 syncprov_done_ctrl( op, rs, ctrls, 0, 0,
3370 NULL, LDAP_SYNC_REFRESH_DELETES );
3371 rs->sr_ctrls = ctrls;
3372 rs->sr_err = LDAP_SUCCESS;
3373 send_ldap_result( op, rs );
3374 rs->sr_ctrls = NULL;
3375 if ( numcsns ) {
3376 ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
3377 op->o_tmpfree( sids, op->o_tmpmemctx );
3378 }
3379 return rs->sr_err;
3380 }
3381 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3382 "no change, skipping log replay\n",
3383 op->o_log_prefix );
3384 goto shortcut;
3385 }
3386
3387 if ( !BER_BVISNULL( &si->si_logbase ) ) {
3388 do_present = 0;
3389 if ( syncprov_play_accesslog( op, rs, srs, ctxcsn,
3390 numcsns, sids, &mincsn, minsid ) ) {
3391 do_present = SS_PRESENT;
3392 }
3393 } else if ( si->si_logs ) {
3394 do_present = 0;
3395 if ( syncprov_play_sessionlog( op, rs, srs, ctxcsn,
3396 numcsns, sids, &mincsn, minsid ) ) {
3397 do_present = SS_PRESENT;
3398 }
3399 } else if ( ad_minCSN != NULL && si->si_nopres && si->si_usehint ) {
3400 /* We are instructed to trust minCSN if it exists. */
3401 Entry *e;
3402 Attribute *a = NULL;
3403 int rc;
3404
3405 /*
3406 * ITS#9580 FIXME: when we've figured out and split the
3407 * sessionlog/deltalog tracking, use the appropriate attribute
3408 */
3409 rc = overlay_entry_get_ov( op, &op->o_bd->be_nsuffix[0], NULL,
3410 ad_minCSN, 0, &e, on );
3411 if ( rc == LDAP_SUCCESS && e != NULL ) {
3412 a = attr_find( e->e_attrs, ad_minCSN );
3413 }
3414
3415 if ( a != NULL ) {
3416 int *minsids;
3417
3418 minsids = slap_parse_csn_sids( a->a_vals, a->a_numvals, op->o_tmpmemctx );
3419 slap_sort_csn_sids( a->a_vals, minsids, a->a_numvals, op->o_tmpmemctx );
3420
3421 for ( i=0, j=0; i < a->a_numvals; i++ ) {
3422 while ( j < numcsns && minsids[i] > sids[j] ) j++;
3423 if ( j < numcsns && minsids[i] == sids[j] &&
3424 ber_bvcmp( &a->a_vals[i], &srs->sr_state.ctxcsn[j] ) <= 0 ) {
3425 /* minCSN for this serverID is contained, keep going */
3426 continue;
3427 }
3428 /*
3429 * Log DB's minCSN claims we can only replay from a certain
3430 * CSN for this serverID, but consumer's cookie hasn't met that
3431 * threshold: they need to refresh
3432 */
3433 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3434 "consumer not within recorded mincsn for DB's mincsn=%s\n",
3435 op->o_log_prefix, a->a_vals[i].bv_val );
3436 rs->sr_err = LDAP_SYNC_REFRESH_REQUIRED;
3437 rs->sr_text = "sync cookie is stale";
3438 slap_sl_free( minsids, op->o_tmpmemctx );
3439 overlay_entry_release_ov( op, e, 0, on );
3440 goto bailout;
3441 }
3442 slap_sl_free( minsids, op->o_tmpmemctx );
3443 }
3444 if ( e != NULL )
3445 overlay_entry_release_ov( op, e, 0, on );
3446 }
3447
3448 /*
3449 * If sessionlog wasn't useful, see if we can find at least one entry
3450 * that hasn't changed based on the cookie.
3451 *
3452 * TODO: Using mincsn only (rather than the whole cookie) will
3453 * under-approximate the set of entries that haven't changed, but we
3454 * can't look up CSNs by serverid with the current indexing support.
3455 *
3456 * As a result, dormant serverids in the cluster become mincsns and
3457 * more likely to make syncprov_findcsn(,FIND_CSN,) fail -> triggering
3458 * an expensive refresh...
3459 */
3460 if ( !do_present ) {
3461 gotstate = 1;
3462 } else if ( syncprov_findcsn( op, FIND_CSN, &mincsn ) != LDAP_SUCCESS ) {
3463 /* No, so a reload is required */
3464 /* the 2.2 consumer doesn't send this hint */
3465 if ( si->si_usehint && srs->sr_rhint == 0 ) {
3466 rs->sr_err = LDAP_SYNC_REFRESH_REQUIRED;
3467 rs->sr_text = "sync cookie is stale";
3468 goto bailout;
3469 }
3470 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3471 "failed to find entry with csn=%s, ignoring cookie\n",
3472 op->o_log_prefix, mincsn.bv_val );
3473 if ( srs->sr_state.ctxcsn ) {
3474 ber_bvarray_free_x( srs->sr_state.ctxcsn, op->o_tmpmemctx );
3475 srs->sr_state.ctxcsn = NULL;
3476 }
3477 if ( srs->sr_state.sids ) {
3478 slap_sl_free( srs->sr_state.sids, op->o_tmpmemctx );
3479 srs->sr_state.sids = NULL;
3480 }
3481 srs->sr_state.numcsns = 0;
3482 } else {
3483 gotstate = 1;
3484 /* If changed and doing Present lookup, send Present UUIDs */
3485 if ( syncprov_findcsn( op, FIND_PRESENT, 0 ) != LDAP_SUCCESS )
3486 goto bailout;
3487 }
3488 } else {
3489 /* The consumer knows nothing, we know nothing. OK. */
3490 if (!numcsns)
3491 goto no_change;
3492 /* No consumer state, assume something has changed */
3493 changed = SS_CHANGED;
3494 }
3495
3496 shortcut:
3497 /* Append CSN range to search filter, save original filter
3498 * for persistent search evaluation
3499 */
3500 if ( sop ) {
3501 ldap_pvt_thread_mutex_lock( &sop->s_mutex );
3502 sop->s_filterstr = op->ors_filterstr;
3503 /* correct the refcount that was set to 2 before */
3504 sop->s_inuse--;
3505 }
3506
3507 /* If something changed, find the changes */
3508 if ( gotstate && ( changed || dirty ) ) {
3509 Filter *fand, *fava;
3510
3511 fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
3512 fand->f_choice = LDAP_FILTER_AND;
3513 fand->f_next = NULL;
3514 fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
3515 fand->f_and = fava;
3516 fava->f_choice = LDAP_FILTER_GE;
3517 fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
3518 fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
3519 #ifdef LDAP_COMP_MATCH
3520 fava->f_ava->aa_cf = NULL;
3521 #endif
3522 ber_dupbv_x( &fava->f_ava->aa_value, &mincsn, op->o_tmpmemctx );
3523 fava->f_next = op->ors_filter;
3524 op->ors_filter = fand;
3525 filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
3526 if ( sop ) {
3527 sop->s_flags |= PS_FIX_FILTER;
3528 }
3529 }
3530 if ( sop ) {
3531 ldap_pvt_thread_mutex_unlock( &sop->s_mutex );
3532 }
3533
3534 /* Let our callback add needed info to returned entries */
3535 cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
3536 ss = (searchstate *)(cb+1);
3537 ss->ss_on = on;
3538 ss->ss_so = sop;
3539 ss->ss_flags = do_present | changed;
3540 ss->ss_ctxcsn = ctxcsn;
3541 ss->ss_numcsns = numcsns;
3542 ss->ss_sids = sids;
3543 cb->sc_response = syncprov_search_response;
3544 cb->sc_cleanup = syncprov_search_cleanup;
3545 cb->sc_private = ss;
3546 cb->sc_next = op->o_callback;
3547 op->o_callback = cb;
3548
3549 /* If this is a persistent search and no changes were reported during
3550 * the refresh phase, just invoke the response callback to transition
3551 * us into persist phase
3552 */
3553 if ( !changed && !dirty ) {
3554 Debug( LDAP_DEBUG_SYNC, "%s syncprov_op_search: "
3555 "nothing changed, finishing up initial search early\n",
3556 op->o_log_prefix );
3557 rs->sr_err = LDAP_SUCCESS;
3558 rs->sr_nentries = 0;
3559 send_ldap_result( op, rs );
3560 return rs->sr_err;
3561 }
3562 return SLAP_CB_CONTINUE;
3563 }
3564
3565 static int
3566 syncprov_operational(
3567 Operation *op,
3568 SlapReply *rs )
3569 {
3570 slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
3571 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
3572
3573 /* This prevents generating unnecessarily; frontend will strip
3574 * any statically stored copy.
3575 */
3576 if ( op->o_sync != SLAP_CONTROL_NONE )
3577 return SLAP_CB_CONTINUE;
3578
3579 if ( rs->sr_entry &&
3580 dn_match( &rs->sr_entry->e_nname, &si->si_contextdn )) {
3581
3582 if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
3583 ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
3584 Attribute *a, **ap = NULL;
3585
3586 for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
3587 if ( a->a_desc == slap_schema.si_ad_contextCSN )
3588 break;
3589 }
3590
3591 ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
3592 if ( si->si_ctxcsn ) {
3593 if ( !a ) {
3594 for ( ap = &rs->sr_operational_attrs; *ap;
3595 ap=&(*ap)->a_next );
3596
3597 a = attr_alloc( slap_schema.si_ad_contextCSN );
3598 *ap = a;
3599 }
3600
3601 if ( !ap ) {
3602 if ( rs_entry2modifiable( op, rs, on )) {
3603 a = attr_find( rs->sr_entry->e_attrs,
3604 slap_schema.si_ad_contextCSN );
3605 }
3606 if ( a->a_nvals != a->a_vals ) {
3607 ber_bvarray_free( a->a_nvals );
3608 }
3609 a->a_nvals = NULL;
3610 ber_bvarray_free( a->a_vals );
3611 a->a_vals = NULL;
3612 a->a_numvals = 0;
3613 }
3614 attr_valadd( a, si->si_ctxcsn, si->si_ctxcsn, si->si_numcsns );
3615 }
3616 ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
3617 }
3618 }
3619 return SLAP_CB_CONTINUE;
3620 }
3621
3622 static int
3623 syncprov_setup_accesslog(void)
3624 {
3625 const char *text;
3626 int rc = -1;
3627
3628 if ( !ad_reqType ) {
3629 if ( slap_str2ad( "reqType", &ad_reqType, &text ) ) {
3630 Debug( LDAP_DEBUG_ANY, "syncprov_setup_accesslog: "
3631 "couldn't get definition for attribute reqType, "
3632 "is accesslog configured?\n" );
3633 return rc;
3634 }
3635 }
3636
3637 if ( !ad_reqResult ) {
3638 if ( slap_str2ad( "reqResult", &ad_reqResult, &text ) ) {
3639 Debug( LDAP_DEBUG_ANY, "syncprov_setup_accesslog: "
3640 "couldn't get definition for attribute reqResult, "
3641 "is accesslog configured?\n" );
3642 return rc;
3643 }
3644 }
3645
3646 if ( !ad_reqDN ) {
3647 if ( slap_str2ad( "reqDN", &ad_reqDN, &text ) ) {
3648 Debug( LDAP_DEBUG_ANY, "syncprov_setup_accesslog: "
3649 "couldn't get definition for attribute reqDN, "
3650 "is accesslog configured?\n" );
3651 return rc;
3652 }
3653 }
3654
3655 if ( !ad_reqEntryUUID ) {
3656 if ( slap_str2ad( "reqEntryUUID", &ad_reqEntryUUID, &text ) ) {
3657 Debug( LDAP_DEBUG_ANY, "syncprov_setup_accesslog: "
3658 "couldn't get definition for attribute reqEntryUUID, "
3659 "is accesslog configured?\n" );
3660 return rc;
3661 }
3662 }
3663
3664 if ( !ad_reqNewDN ) {
3665 if ( slap_str2ad( "reqNewDN", &ad_reqNewDN, &text ) ) {
3666 Debug( LDAP_DEBUG_ANY, "syncprov_setup_accesslog: "
3667 "couldn't get definition for attribute reqNewDN, "
3668 "is accessslog configured?\n" );
3669 return rc;
3670 }
3671 }
3672
3673 if ( !ad_minCSN ) {
3674 if ( slap_str2ad( "minCSN", &ad_minCSN, &text ) ) {
3675 Debug( LDAP_DEBUG_ANY, "syncprov_setup_accesslog: "
3676 "couldn't get definition for attribute minCSN, "
3677 "is accessslog configured?\n" );
3678 return rc;
3679 }
3680 }
3681
3682 return LDAP_SUCCESS;
3683 }
3684
3685 enum {
3686 SP_CHKPT = 1,
3687 SP_SESSL,
3688 SP_NOPRES,
3689 SP_USEHINT,
3690 SP_LOGDB
3691 };
3692
3693 static ConfigDriver sp_cf_gen;
3694
3695 static ConfigTable spcfg[] = {
3696 { "syncprov-checkpoint", "ops> <minutes", 3, 3, 0, ARG_MAGIC|SP_CHKPT,
3697 sp_cf_gen, "( OLcfgOvAt:1.1 NAME 'olcSpCheckpoint' "
3698 "DESC 'ContextCSN checkpoint interval in ops and minutes' "
3699 "EQUALITY caseIgnoreMatch "
3700 "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
3701 { "syncprov-sessionlog", "ops", 2, 2, 0, ARG_INT|ARG_MAGIC|SP_SESSL,
3702 sp_cf_gen, "( OLcfgOvAt:1.2 NAME 'olcSpSessionlog' "
3703 "DESC 'Session log size in ops' "
3704 "EQUALITY integerMatch "
3705 "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
3706 { "syncprov-nopresent", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_NOPRES,
3707 sp_cf_gen, "( OLcfgOvAt:1.3 NAME 'olcSpNoPresent' "
3708 "DESC 'Omit Present phase processing' "
3709 "EQUALITY booleanMatch "
3710 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3711 { "syncprov-reloadhint", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_USEHINT,
3712 sp_cf_gen, "( OLcfgOvAt:1.4 NAME 'olcSpReloadHint' "
3713 "DESC 'Observe Reload Hint in Request control' "
3714 "EQUALITY booleanMatch "
3715 "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
3716 { "syncprov-sessionlog-source", NULL, 2, 2, 0, ARG_DN|ARG_QUOTE|ARG_MAGIC|SP_LOGDB,
3717 sp_cf_gen, "( OLcfgOvAt:1.5 NAME 'olcSpSessionlogSource' "
3718 "DESC 'On startup, try loading sessionlog from this subtree' "
3719 "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
3720 { NULL, NULL, 0, 0, 0, ARG_IGNORED }
3721 };
3722
3723 static ConfigOCs spocs[] = {
3724 { "( OLcfgOvOc:1.1 "
3725 "NAME 'olcSyncProvConfig' "
3726 "DESC 'SyncRepl Provider configuration' "
3727 "SUP olcOverlayConfig "
3728 "MAY ( olcSpCheckpoint "
3729 "$ olcSpSessionlog "
3730 "$ olcSpNoPresent "
3731 "$ olcSpReloadHint "
3732 "$ olcSpSessionlogSource "
3733 ") )",
3734 Cft_Overlay, spcfg },
3735 { NULL, 0, NULL }
3736 };
3737
3738 static int
3739 sp_cf_gen(ConfigArgs *c)
3740 {
3741 slap_overinst *on = (slap_overinst *)c->bi;
3742 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
3743 int rc = 0;
3744
3745 if ( c->op == SLAP_CONFIG_EMIT ) {
3746 switch ( c->type ) {
3747 case SP_CHKPT:
3748 if ( si->si_chkops || si->si_chktime ) {
3749 struct berval bv;
3750 /* we assume si_chktime is a multiple of 60
3751 * because the parsed value was originally
3752 * multiplied by 60 */
3753 bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
3754 "%d %d", si->si_chkops, si->si_chktime/60 );
3755 if ( bv.bv_len >= sizeof( c->cr_msg ) ) {
3756 rc = 1;
3757 } else {
3758 bv.bv_val = c->cr_msg;
3759 value_add_one( &c->rvalue_vals, &bv );
3760 }
3761 } else {
3762 rc = 1;
3763 }
3764 break;
3765 case SP_SESSL:
3766 if ( si->si_logs ) {
3767 c->value_int = si->si_logs->sl_size;
3768 } else {
3769 rc = 1;
3770 }
3771 break;
3772 case SP_NOPRES:
3773 if ( si->si_nopres ) {
3774 c->value_int = 1;
3775 } else {
3776 rc = 1;
3777 }
3778 break;
3779 case SP_USEHINT:
3780 if ( si->si_usehint ) {
3781 c->value_int = 1;
3782 } else {
3783 rc = 1;
3784 }
3785 break;
3786 case SP_LOGDB:
3787 if ( BER_BVISEMPTY( &si->si_logbase ) ) {
3788 rc = 1;
3789 } else {
3790 value_add_one( &c->rvalue_vals, &si->si_logbase );
3791 value_add_one( &c->rvalue_nvals, &si->si_logbase );
3792 }
3793 break;
3794 }
3795 return rc;
3796 } else if ( c->op == LDAP_MOD_DELETE ) {
3797 switch ( c->type ) {
3798 case SP_CHKPT:
3799 si->si_chkops = 0;
3800 si->si_chktime = 0;
3801 break;
3802 case SP_SESSL:
3803 if ( si->si_logs )
3804 si->si_logs->sl_size = 0;
3805 break;
3806 case SP_NOPRES:
3807 si->si_nopres = 0;
3808 break;
3809 case SP_USEHINT:
3810 si->si_usehint = 0;
3811 break;
3812 case SP_LOGDB:
3813 if ( !BER_BVISNULL( &si->si_logbase ) ) {
3814 ch_free( si->si_logbase.bv_val );
3815 BER_BVZERO( &si->si_logbase );
3816 }
3817 break;
3818 }
3819 return rc;
3820 }
3821 switch ( c->type ) {
3822 case SP_CHKPT:
3823 if ( lutil_atoi( &si->si_chkops, c->argv[1] ) != 0 ) {
3824 snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint ops # \"%s\"",
3825 c->argv[0], c->argv[1] );
3826 Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
3827 "%s: %s\n", c->log, c->cr_msg );
3828 return ARG_BAD_CONF;
3829 }
3830 if ( si->si_chkops <= 0 ) {
3831 snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint ops # \"%d\"",
3832 c->argv[0], si->si_chkops );
3833 Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
3834 "%s: %s\n", c->log, c->cr_msg );
3835 return ARG_BAD_CONF;
3836 }
3837 if ( lutil_atoi( &si->si_chktime, c->argv[2] ) != 0 ) {
3838 snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint time \"%s\"",
3839 c->argv[0], c->argv[1] );
3840 Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
3841 "%s: %s\n", c->log, c->cr_msg );
3842 return ARG_BAD_CONF;
3843 }
3844 if ( si->si_chktime <= 0 ) {
3845 snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint time \"%d\"",
3846 c->argv[0], si->si_chkops );
3847 Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
3848 "%s: %s\n", c->log, c->cr_msg );
3849 return ARG_BAD_CONF;
3850 }
3851 si->si_chktime *= 60;
3852 break;
3853 case SP_SESSL: {
3854 sessionlog *sl;
3855 int size = c->value_int;
3856
3857 if ( size < 0 ) {
3858 snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s size %d is negative",
3859 c->argv[0], size );
3860 Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
3861 "%s: %s\n", c->log, c->cr_msg );
3862 return ARG_BAD_CONF;
3863 }
3864 if ( size && !BER_BVISNULL( &si->si_logbase ) ) {
3865 Debug( LDAP_DEBUG_ANY, "syncprov_config: while configuring "
3866 "internal sessionlog, accesslog source has already been "
3867 "configured, this results in wasteful operation\n" );
3868 }
3869 sl = si->si_logs;
3870 if ( !sl ) {
3871 if ( !size ) break;
3872 sl = ch_calloc( 1, sizeof( sessionlog ));
3873 ldap_pvt_thread_rdwr_init( &sl->sl_mutex );
3874 si->si_logs = sl;
3875 }
3876 sl->sl_size = size;
3877 }
3878 break;
3879 case SP_NOPRES:
3880 si->si_nopres = c->value_int;
3881 if ( si->si_nopres ) {
3882 /* Consider we might be a delta provider, but it's ok if not */
3883 (void)syncprov_setup_accesslog();
3884 }
3885 break;
3886 case SP_USEHINT:
3887 si->si_usehint = c->value_int;
3888 break;
3889 case SP_LOGDB:
3890 if ( si->si_logs ) {
3891 Debug( LDAP_DEBUG_ANY, "syncprov_config: while configuring "
3892 "accesslog source, internal sessionlog has already been "
3893 "configured, this results in wasteful operation\n" );
3894 }
3895 if ( CONFIG_ONLINE_ADD( c ) ) {
3896 if ( !select_backend( &c->value_ndn, 0 ) ) {
3897 snprintf( c->cr_msg, sizeof( c->cr_msg ),
3898 "<%s> no matching backend found for suffix",
3899 c->argv[0] );
3900 Debug( LDAP_DEBUG_ANY, "%s: %s \"%s\"\n",
3901 c->log, c->cr_msg, c->value_dn.bv_val );
3902 rc = 1;
3903 break;
3904 }
3905 ch_free( c->value_ndn.bv_val );
3906 }
3907 si->si_logbase = c->value_ndn;
3908 rc = syncprov_setup_accesslog();
3909 ch_free( c->value_dn.bv_val );
3910 break;
3911 }
3912 return rc;
3913 }
3914
3915 /* ITS#3456 we cannot run this search on the main thread, must use a
3916 * child thread in order to insure we have a big enough stack.
3917 */
3918 static void *
3919 syncprov_db_otask(
3920 void *ptr
3921 )
3922 {
3923 syncprov_findcsn( ptr, FIND_MAXCSN, 0 );
3924 return NULL;
3925 }
3926
3927 static int
3928 syncprov_db_ocallback(
3929 Operation *op,
3930 SlapReply *rs
3931 )
3932 {
3933 if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
3934 if ( rs->sr_entry->e_name.bv_len )
3935 op->o_callback->sc_private = (void *)1;
3936 }
3937 return LDAP_SUCCESS;
3938 }
3939
3940 /* ITS#9015 see if the DB is really empty */
3941 static void *
3942 syncprov_db_otask2(
3943 void *ptr
3944 )
3945 {
3946 Operation *op = ptr;
3947 SlapReply rs = {REP_RESULT};
3948 slap_callback cb = {0};
3949 int rc;
3950
3951 cb.sc_response = syncprov_db_ocallback;
3952
3953 op->o_managedsait = SLAP_CONTROL_CRITICAL;
3954 op->o_callback = &cb;
3955 op->o_tag = LDAP_REQ_SEARCH;
3956 op->ors_scope = LDAP_SCOPE_SUBTREE;
3957 op->ors_limit = NULL;
3958 op->ors_slimit = 1;
3959 op->ors_tlimit = SLAP_NO_LIMIT;
3960 op->ors_attrs = slap_anlist_no_attrs;
3961 op->ors_attrsonly = 1;
3962 op->ors_deref = LDAP_DEREF_NEVER;
3963 op->ors_filter = &generic_filter;
3964 op->ors_filterstr = generic_filterstr;
3965 rc = op->o_bd->be_search( op, &rs );
3966 if ( rc == LDAP_SIZELIMIT_EXCEEDED || cb.sc_private )
3967 op->ors_slimit = 2;
3968 return NULL;
3969 }
3970
3971 /* Read any existing contextCSN from the underlying db.
3972 * Then search for any entries newer than that. If no value exists,
3973 * just generate it. Cache whatever result.
3974 */
3975 static int
3976 syncprov_db_open(
3977 BackendDB *be,
3978 ConfigReply *cr
3979 )
3980 {
3981 slap_overinst *on = (slap_overinst *) be->bd_info;
3982 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
3983
3984 Connection conn = { 0 };
3985 OperationBuffer opbuf;
3986 Operation *op;
3987 Entry *e = NULL;
3988 Attribute *a;
3989 int rc;
3990 void *thrctx = NULL;
3991
3992 if ( !SLAP_LASTMOD( be )) {
3993 Debug( LDAP_DEBUG_ANY,
3994 "syncprov_db_open: invalid config, lastmod must be enabled\n" );
3995 return -1;
3996 }
3997
3998 if ( slapMode & SLAP_TOOL_MODE ) {
3999 return 0;
4000 }
4001
4002 rc = overlay_register_control( be, LDAP_CONTROL_SYNC );
4003 if ( rc ) {
4004 return rc;
4005 }
4006
4007 Debug( LDAP_DEBUG_SYNC, "syncprov_db_open: "
4008 "starting syncprov for suffix %s\n",
4009 be->be_suffix[0].bv_val );
4010
4011 thrctx = ldap_pvt_thread_pool_context();
4012 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4013 op = &opbuf.ob_op;
4014 op->o_bd = be;
4015 op->o_dn = be->be_rootdn;
4016 op->o_ndn = be->be_rootndn;
4017
4018 if ( SLAP_SYNC_SUBENTRY( be )) {
4019 build_new_dn( &si->si_contextdn, be->be_nsuffix,
4020 (struct berval *)&slap_ldapsync_cn_bv, NULL );
4021 } else {
4022 si->si_contextdn = be->be_nsuffix[0];
4023 }
4024 rc = overlay_entry_get_ov( op, &si->si_contextdn, NULL,
4025 slap_schema.si_ad_contextCSN, 0, &e, on );
4026
4027 if ( e ) {
4028 ldap_pvt_thread_t tid;
4029
4030 a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
4031 if ( a ) {
4032 ber_bvarray_dup_x( &si->si_ctxcsn, a->a_vals, NULL );
4033 si->si_numcsns = a->a_numvals;
4034 si->si_sids = slap_parse_csn_sids( si->si_ctxcsn, a->a_numvals, NULL );
4035 slap_sort_csn_sids( si->si_ctxcsn, si->si_sids, si->si_numcsns, NULL );
4036 }
4037 overlay_entry_release_ov( op, e, 0, on );
4038 if ( si->si_ctxcsn && !SLAP_DBCLEAN( be )) {
4039 op->o_tag = LDAP_REQ_SEARCH;
4040 op->o_req_dn = be->be_suffix[0];
4041 op->o_req_ndn = be->be_nsuffix[0];
4042 op->ors_scope = LDAP_SCOPE_SUBTREE;
4043 ldap_pvt_thread_create( &tid, 0, syncprov_db_otask, op );
4044 ldap_pvt_thread_join( tid, NULL );
4045 }
4046 }
4047
4048 /* Didn't find a contextCSN, should we generate one? */
4049 if ( !si->si_ctxcsn ) {
4050 char csnbuf[ LDAP_PVT_CSNSTR_BUFSIZE ];
4051 struct berval csn;
4052
4053 if ( SLAP_SINGLE_SHADOW( op->o_bd ) ) {
4054 /* Not in charge of this serverID, don't generate anything. */
4055 goto out;
4056 }
4057 if ( !SLAP_SYNC_SUBENTRY( be ) && rc != LDAP_SUCCESS
4058 && rc != LDAP_NO_SUCH_ATTRIBUTE ) {
4059 /* If the DB is genuinely empty, don't generate one either. */
4060 goto out;
4061 }
4062 if ( !si->si_contextdn.bv_len ) {
4063 ldap_pvt_thread_t tid;
4064 /* a glue entry here with no contextCSN might mean an empty DB.
4065 * we need to search for children, to be sure.
4066 */
4067 op->o_req_dn = be->be_suffix[0];
4068 op->o_req_ndn = be->be_nsuffix[0];
4069 op->o_bd->bd_info = (BackendInfo *)on->on_info;
4070 ldap_pvt_thread_create( &tid, 0, syncprov_db_otask2, op );
4071 ldap_pvt_thread_join( tid, NULL );
4072 if ( op->ors_slimit == 1 )
4073 goto out;
4074 }
4075
4076 csn.bv_val = csnbuf;
4077 csn.bv_len = sizeof( csnbuf );
4078 slap_get_csn( op, &csn, 0 );
4079 value_add_one( &si->si_ctxcsn, &csn );
4080 si->si_numcsns = 1;
4081 si->si_sids = ch_malloc( sizeof(int) );
4082 si->si_sids[0] = slap_serverID;
4083 Debug( LDAP_DEBUG_SYNC, "syncprov_db_open: "
4084 "generated a new ctxcsn=%s for suffix %s\n",
4085 csn.bv_val, be->be_suffix[0].bv_val );
4086
4087 /* make sure we do a checkpoint on close */
4088 si->si_numops++;
4089 }
4090
4091 /* Initialize the sessionlog mincsn */
4092 if ( si->si_logs && si->si_numcsns ) {
4093 sessionlog *sl = si->si_logs;
4094 int i;
4095 ber_bvarray_dup_x( &sl->sl_mincsn, si->si_ctxcsn, NULL );
4096 sl->sl_numcsns = si->si_numcsns;
4097 sl->sl_sids = ch_malloc( si->si_numcsns * sizeof(int) );
4098 for ( i=0; i < si->si_numcsns; i++ )
4099 sl->sl_sids[i] = si->si_sids[i];
4100 }
4101
4102 if ( !BER_BVISNULL( &si->si_logbase ) ) {
4103 BackendDB *db = select_backend( &si->si_logbase, 0 );
4104 if ( !db ) {
4105 Debug( LDAP_DEBUG_ANY, "syncprov_db_open: "
4106 "configured accesslog database dn='%s' not present\n",
4107 si->si_logbase.bv_val );
4108 return -1;
4109 }
4110 }
4111
4112 out:
4113 op->o_bd->bd_info = (BackendInfo *)on;
4114 return 0;
4115 }
4116
4117 /* Write the current contextCSN into the underlying db.
4118 */
4119 static int
4120 syncprov_db_close(
4121 BackendDB *be,
4122 ConfigReply *cr
4123 )
4124 {
4125 slap_overinst *on = (slap_overinst *) be->bd_info;
4126 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
4127 #ifdef SLAP_CONFIG_DELETE
4128 syncops *so, *sonext;
4129 #endif /* SLAP_CONFIG_DELETE */
4130
4131 if ( slapMode & SLAP_TOOL_MODE ) {
4132 return 0;
4133 }
4134 if ( si->si_numops ) {
4135 Connection conn = {0};
4136 OperationBuffer opbuf;
4137 Operation *op;
4138 void *thrctx;
4139
4140 thrctx = ldap_pvt_thread_pool_context();
4141 connection_fake_init2( &conn, &opbuf, thrctx, 0 );
4142 op = &opbuf.ob_op;
4143 op->o_bd = be;
4144 op->o_dn = be->be_rootdn;
4145 op->o_ndn = be->be_rootndn;
4146 syncprov_checkpoint( op, on );
4147 }
4148
4149 #ifdef SLAP_CONFIG_DELETE
4150 if ( !slapd_shutdown ) {
4151 ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
4152 for ( so=si->si_ops, sonext=so; so; so=sonext ) {
4153 SlapReply rs = {REP_RESULT};
4154 rs.sr_err = LDAP_UNAVAILABLE;
4155 ldap_pvt_thread_mutex_lock( &so->s_mutex );
4156 send_ldap_result( so->s_op, &rs );
4157 sonext=so->s_next;
4158 if ( so->s_flags & PS_TASK_QUEUED )
4159 ldap_pvt_thread_pool_retract( so->s_pool_cookie );
4160 ldap_pvt_thread_mutex_unlock( &so->s_mutex );
4161 if ( !syncprov_drop_psearch( so, 0 ))
4162 so->s_si = NULL;
4163 }
4164 si->si_ops=NULL;
4165 ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
4166 }
4167 overlay_unregister_control( be, LDAP_CONTROL_SYNC );
4168 #endif /* SLAP_CONFIG_DELETE */
4169
4170 return 0;
4171 }
4172
4173 static int
4174 syncprov_db_init(
4175 BackendDB *be,
4176 ConfigReply *cr
4177 )
4178 {
4179 slap_overinst *on = (slap_overinst *)be->bd_info;
4180 syncprov_info_t *si;
4181
4182 if ( SLAP_ISGLOBALOVERLAY( be ) ) {
4183 Debug( LDAP_DEBUG_ANY,
4184 "syncprov must be instantiated within a database.\n" );
4185 return 1;
4186 }
4187
4188 si = ch_calloc(1, sizeof(syncprov_info_t));
4189 on->on_bi.bi_private = si;
4190 ldap_pvt_thread_rdwr_init( &si->si_csn_rwlock );
4191 ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
4192 ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
4193 ldap_pvt_thread_mutex_init( &si->si_resp_mutex );
4194
4195 csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
4196 csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
4197 csn_anlist[1].an_desc = slap_schema.si_ad_entryUUID;
4198 csn_anlist[1].an_name = slap_schema.si_ad_entryUUID->ad_cname;
4199
4200 uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
4201 uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
4202
4203 return 0;
4204 }
4205
4206 static int
4207 syncprov_db_destroy(
4208 BackendDB *be,
4209 ConfigReply *cr
4210 )
4211 {
4212 slap_overinst *on = (slap_overinst *)be->bd_info;
4213 syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
4214
4215 if ( si ) {
4216 if ( si->si_logs ) {
4217 sessionlog *sl = si->si_logs;
4218
4219 ldap_tavl_free( sl->sl_entries, (AVL_FREE)ch_free );
4220 if ( sl->sl_mincsn )
4221 ber_bvarray_free( sl->sl_mincsn );
4222 if ( sl->sl_sids )
4223 ch_free( sl->sl_sids );
4224
4225 ldap_pvt_thread_rdwr_destroy(&si->si_logs->sl_mutex);
4226 ch_free( si->si_logs );
4227 }
4228 if ( si->si_ctxcsn )
4229 ber_bvarray_free( si->si_ctxcsn );
4230 if ( si->si_sids )
4231 ch_free( si->si_sids );
4232 if ( si->si_logbase.bv_val )
4233 ch_free( si->si_logbase.bv_val );
4234 ldap_pvt_thread_mutex_destroy( &si->si_resp_mutex );
4235 ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
4236 ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
4237 ldap_pvt_thread_rdwr_destroy( &si->si_csn_rwlock );
4238 ch_free( si );
4239 }
4240
4241 return 0;
4242 }
4243
4244 static int syncprov_parseCtrl (
4245 Operation *op,
4246 SlapReply *rs,
4247 LDAPControl *ctrl )
4248 {
4249 ber_tag_t tag;
4250 BerElementBuffer berbuf;
4251 BerElement *ber = (BerElement *)&berbuf;
4252 ber_int_t mode;
4253 ber_len_t len;
4254 struct berval cookie = BER_BVNULL;
4255 sync_control *sr;
4256 int rhint = 0;
4257
4258 if ( op->o_sync != SLAP_CONTROL_NONE ) {
4259 rs->sr_text = "Sync control specified multiple times";
4260 return LDAP_PROTOCOL_ERROR;
4261 }
4262
4263 if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
4264 rs->sr_text = "Sync control specified with pagedResults control";
4265 return LDAP_PROTOCOL_ERROR;
4266 }
4267
4268 if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
4269 rs->sr_text = "Sync control value is absent";
4270 return LDAP_PROTOCOL_ERROR;
4271 }
4272
4273 if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
4274 rs->sr_text = "Sync control value is empty";
4275 return LDAP_PROTOCOL_ERROR;
4276 }
4277
4278 /* Parse the control value
4279 * syncRequestValue ::= SEQUENCE {
4280 * mode ENUMERATED {
4281 * -- 0 unused
4282 * refreshOnly (1),
4283 * -- 2 reserved
4284 * refreshAndPersist (3)
4285 * },
4286 * cookie syncCookie OPTIONAL
4287 * }
4288 */
4289
4290 ber_init2( ber, &ctrl->ldctl_value, 0 );
4291
4292 if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
4293 rs->sr_text = "Sync control : mode decoding error";
4294 return LDAP_PROTOCOL_ERROR;
4295 }
4296
4297 switch( mode ) {
4298 case LDAP_SYNC_REFRESH_ONLY:
4299 mode = SLAP_SYNC_REFRESH;
4300 break;
4301 case LDAP_SYNC_REFRESH_AND_PERSIST:
4302 mode = SLAP_SYNC_REFRESH_AND_PERSIST;
4303 break;
4304 default:
4305 rs->sr_text = "Sync control : unknown update mode";
4306 return LDAP_PROTOCOL_ERROR;
4307 }
4308
4309 tag = ber_peek_tag( ber, &len );
4310
4311 if ( tag == LDAP_TAG_SYNC_COOKIE ) {
4312 if (( ber_scanf( ber, /*{*/ "m", &cookie )) == LBER_ERROR ) {
4313 rs->sr_text = "Sync control : cookie decoding error";
4314 return LDAP_PROTOCOL_ERROR;
4315 }
4316 tag = ber_peek_tag( ber, &len );
4317 }
4318 if ( tag == LDAP_TAG_RELOAD_HINT ) {
4319 if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
4320 rs->sr_text = "Sync control : rhint decoding error";
4321 return LDAP_PROTOCOL_ERROR;
4322 }
4323 }
4324 if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
4325 rs->sr_text = "Sync control : decoding error";
4326 return LDAP_PROTOCOL_ERROR;
4327 }
4328 sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
4329 sr->sr_rhint = rhint;
4330 if (!BER_BVISNULL(&cookie)) {
4331 ber_dupbv_x( &sr->sr_state.octet_str, &cookie, op->o_tmpmemctx );
4332 /* If parse fails, pretend no cookie was sent */
4333 if ( slap_parse_sync_cookie( &sr->sr_state, op->o_tmpmemctx ) ||
4334 sr->sr_state.rid == -1 ) {
4335 if ( sr->sr_state.ctxcsn ) {
4336 ber_bvarray_free_x( sr->sr_state.ctxcsn, op->o_tmpmemctx );
4337 sr->sr_state.ctxcsn = NULL;
4338 }
4339 sr->sr_state.numcsns = 0;
4340 }
4341 }
4342
4343 op->o_controls[slap_cids.sc_LDAPsync] = sr;
4344
4345 op->o_sync = ctrl->ldctl_iscritical
4346 ? SLAP_CONTROL_CRITICAL
4347 : SLAP_CONTROL_NONCRITICAL;
4348
4349 op->o_sync_mode |= mode; /* o_sync_mode shares o_sync */
4350
4351 return LDAP_SUCCESS;
4352 }
4353
4354 /* This overlay is set up for dynamic loading via moduleload. For static
4355 * configuration, you'll need to arrange for the slap_overinst to be
4356 * initialized and registered by some other function inside slapd.
4357 */
4358
4359 static slap_overinst syncprov;
4360
4361 int
4362 syncprov_initialize()
4363 {
4364 int rc;
4365
4366 rc = register_supported_control( LDAP_CONTROL_SYNC,
4367 SLAP_CTRL_SEARCH, NULL,
4368 syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
4369 if ( rc != LDAP_SUCCESS ) {
4370 Debug( LDAP_DEBUG_ANY,
4371 "syncprov_init: Failed to register control %d\n", rc );
4372 return rc;
4373 }
4374
4375 syncprov.on_bi.bi_type = "syncprov";
4376 syncprov.on_bi.bi_flags = SLAPO_BFLAG_SINGLE;
4377 syncprov.on_bi.bi_db_init = syncprov_db_init;
4378 syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
4379 syncprov.on_bi.bi_db_open = syncprov_db_open;
4380 syncprov.on_bi.bi_db_close = syncprov_db_close;
4381
4382 syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
4383 syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
4384
4385 syncprov.on_bi.bi_op_add = syncprov_op_mod;
4386 syncprov.on_bi.bi_op_compare = syncprov_op_compare;
4387 syncprov.on_bi.bi_op_delete = syncprov_op_mod;
4388 syncprov.on_bi.bi_op_modify = syncprov_op_mod;
4389 syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
4390 syncprov.on_bi.bi_op_search = syncprov_op_search;
4391 syncprov.on_bi.bi_extended = syncprov_op_extended;
4392 syncprov.on_bi.bi_operational = syncprov_operational;
4393
4394 syncprov.on_bi.bi_cf_ocs = spocs;
4395
4396 generic_filter.f_desc = slap_schema.si_ad_objectClass;
4397
4398 rc = config_register_schema( spcfg, spocs );
4399 if ( rc ) return rc;
4400
4401 return overlay_register( &syncprov );
4402 }
4403
4404 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
4405 int
4406 init_module( int argc, char *argv[] )
4407 {
4408 return syncprov_initialize();
4409 }
4410 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
4411
4412 #endif /* defined(SLAPD_OVER_SYNCPROV) */