xref: /netbsd-src/external/bsd/openldap/dist/servers/slapd/syncrepl.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*	$NetBSD: syncrepl.c,v 1.1.1.4 2010/12/12 15:22:51 adam Exp $	*/
2 
3 /* syncrepl.c -- Replication Engine which uses the LDAP Sync protocol */
4 /* OpenLDAP: pkg/ldap/servers/slapd/syncrepl.c,v 1.254.2.106 2010/06/10 17:15:14 quanah Exp */
5 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
6  *
7  * Copyright 2003-2010 The OpenLDAP Foundation.
8  * Portions Copyright 2003 by IBM Corporation.
9  * Portions Copyright 2003-2008 by Howard Chu, Symas Corporation.
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted only as authorized by the OpenLDAP
14  * Public License.
15  *
16  * A copy of this license is available in the file LICENSE in the
17  * top-level directory of the distribution or, alternatively, at
18  * <http://www.OpenLDAP.org/license.html>.
19  */
20 
21 #include "portable.h"
22 
23 #include <stdio.h>
24 
25 #include <ac/string.h>
26 #include <ac/socket.h>
27 
28 #include "lutil.h"
29 #include "slap.h"
30 #include "lutil_ldap.h"
31 
32 #include "config.h"
33 
34 #include "ldap_rq.h"
35 
36 struct nonpresent_entry {
37 	struct berval *npe_name;
38 	struct berval *npe_nname;
39 	LDAP_LIST_ENTRY(nonpresent_entry) npe_link;
40 };
41 
42 typedef struct cookie_state {
43 	ldap_pvt_thread_mutex_t	cs_mutex;
44 	int	cs_num;
45 	int cs_age;
46 	int cs_ref;
47 	struct berval *cs_vals;
48 	int *cs_sids;
49 
50 	/* pending changes, not yet committed */
51 	ldap_pvt_thread_mutex_t	cs_pmutex;
52 	int	cs_pnum;
53 	struct berval *cs_pvals;
54 	int *cs_psids;
55 } cookie_state;
56 
57 #define	SYNCDATA_DEFAULT	0	/* entries are plain LDAP entries */
58 #define	SYNCDATA_ACCESSLOG	1	/* entries are accesslog format */
59 #define	SYNCDATA_CHANGELOG	2	/* entries are changelog format */
60 
61 #define	SYNCLOG_LOGGING		0	/* doing a log-based update */
62 #define	SYNCLOG_FALLBACK	1	/* doing a full refresh */
63 
64 #define RETRYNUM_FOREVER	(-1)	/* retry forever */
65 #define RETRYNUM_TAIL		(-2)	/* end of retrynum array */
66 #define RETRYNUM_VALID(n)	((n) >= RETRYNUM_FOREVER)	/* valid retrynum */
67 #define RETRYNUM_FINITE(n)	((n) > RETRYNUM_FOREVER)	/* not forever */
68 
69 typedef struct syncinfo_s {
70 	struct syncinfo_s	*si_next;
71 	BackendDB		*si_be;
72 	BackendDB		*si_wbe;
73 	struct re_s		*si_re;
74 	int			si_rid;
75 	char			si_ridtxt[ STRLENOF("rid=999") + 1 ];
76 	slap_bindconf		si_bindconf;
77 	struct berval		si_base;
78 	struct berval		si_logbase;
79 	struct berval		si_filterstr;
80 	Filter			*si_filter;
81 	struct berval		si_logfilterstr;
82 	struct berval		si_contextdn;
83 	int			si_scope;
84 	int			si_attrsonly;
85 	char			*si_anfile;
86 	AttributeName		*si_anlist;
87 	AttributeName		*si_exanlist;
88 	char 			**si_attrs;
89 	char			**si_exattrs;
90 	int			si_allattrs;
91 	int			si_allopattrs;
92 	int			si_schemachecking;
93 	int			si_type;	/* the active type */
94 	int			si_ctype;	/* the configured type */
95 	time_t			si_interval;
96 	time_t			*si_retryinterval;
97 	int			*si_retrynum_init;
98 	int			*si_retrynum;
99 	struct sync_cookie	si_syncCookie;
100 	cookie_state		*si_cookieState;
101 	int			si_cookieAge;
102 	int			si_manageDSAit;
103 	int			si_slimit;
104 	int			si_tlimit;
105 	int			si_refreshDelete;
106 	int			si_refreshPresent;
107 	int			si_refreshDone;
108 	int			si_syncdata;
109 	int			si_logstate;
110 	int			si_got;
111 	ber_int_t	si_msgid;
112 	Avlnode			*si_presentlist;
113 	LDAP			*si_ld;
114 	Connection		*si_conn;
115 	LDAP_LIST_HEAD(np, nonpresent_entry)	si_nonpresentlist;
116 	ldap_pvt_thread_mutex_t	si_mutex;
117 } syncinfo_t;
118 
119 static int syncuuid_cmp( const void *, const void * );
120 static int avl_presentlist_insert( syncinfo_t* si, struct berval *syncUUID );
121 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray, struct sync_cookie *, int );
122 static int syncrepl_message_to_op(
123 					syncinfo_t *, Operation *, LDAPMessage * );
124 static int syncrepl_message_to_entry(
125 					syncinfo_t *, Operation *, LDAPMessage *,
126 					Modifications **, Entry **, int );
127 static int syncrepl_entry(
128 					syncinfo_t *, Operation*, Entry*,
129 					Modifications**,int, struct berval*,
130 					struct berval *cookieCSN );
131 static int syncrepl_updateCookie(
132 					syncinfo_t *, Operation *,
133 					struct sync_cookie * );
134 static struct berval * slap_uuidstr_from_normalized(
135 					struct berval *, struct berval *, void * );
136 static int syncrepl_add_glue_ancestors(
137 	Operation* op, Entry *e );
138 
139 /* callback functions */
140 static int dn_callback( Operation *, SlapReply * );
141 static int nonpresent_callback( Operation *, SlapReply * );
142 static int null_callback( Operation *, SlapReply * );
143 
144 static AttributeDescription *sync_descs[4];
145 
146 static const char *
147 syncrepl_state2str( int state )
148 {
149 	switch ( state ) {
150 	case LDAP_SYNC_PRESENT:
151 		return "PRESENT";
152 
153 	case LDAP_SYNC_ADD:
154 		return "ADD";
155 
156 	case LDAP_SYNC_MODIFY:
157 		return "MODIFY";
158 
159 	case LDAP_SYNC_DELETE:
160 		return "DELETE";
161 	}
162 
163 	return "UNKNOWN";
164 }
165 
166 static void
167 init_syncrepl(syncinfo_t *si)
168 {
169 	int i, j, k, l, n;
170 	char **attrs, **exattrs;
171 
172 	if ( !sync_descs[0] ) {
173 		sync_descs[0] = slap_schema.si_ad_objectClass;
174 		sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
175 		sync_descs[2] = slap_schema.si_ad_entryCSN;
176 		sync_descs[3] = NULL;
177 	}
178 
179 	if ( si->si_allattrs && si->si_allopattrs )
180 		attrs = NULL;
181 	else
182 		attrs = anlist2attrs( si->si_anlist );
183 
184 	if ( attrs ) {
185 		if ( si->si_allattrs ) {
186 			i = 0;
187 			while ( attrs[i] ) {
188 				if ( !is_at_operational( at_find( attrs[i] ) ) ) {
189 					for ( j = i; attrs[j] != NULL; j++ ) {
190 						if ( j == i )
191 							ch_free( attrs[i] );
192 						attrs[j] = attrs[j+1];
193 					}
194 				} else {
195 					i++;
196 				}
197 			}
198 			attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
199 			attrs[i] = ch_strdup("*");
200 			attrs[i + 1] = NULL;
201 
202 		} else if ( si->si_allopattrs ) {
203 			i = 0;
204 			while ( attrs[i] ) {
205 				if ( is_at_operational( at_find( attrs[i] ) ) ) {
206 					for ( j = i; attrs[j] != NULL; j++ ) {
207 						if ( j == i )
208 							ch_free( attrs[i] );
209 						attrs[j] = attrs[j+1];
210 					}
211 				} else {
212 					i++;
213 				}
214 			}
215 			attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
216 			attrs[i] = ch_strdup("+");
217 			attrs[i + 1] = NULL;
218 		}
219 
220 		for ( i = 0; sync_descs[i] != NULL; i++ ) {
221 			j = 0;
222 			while ( attrs[j] ) {
223 				if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
224 					for ( k = j; attrs[k] != NULL; k++ ) {
225 						if ( k == j )
226 							ch_free( attrs[k] );
227 						attrs[k] = attrs[k+1];
228 					}
229 				} else {
230 					j++;
231 				}
232 			}
233 		}
234 
235 		for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
236 
237 		if ( si->si_allopattrs ) {
238 			attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ) );
239 		} else {
240 			attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ) );
241 		}
242 
243 		/* Add Attributes */
244 		if ( si->si_allopattrs ) {
245 			attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
246 		} else {
247 			for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
248 				attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
249 			}
250 		}
251 		attrs[ n ] = NULL;
252 
253 	} else {
254 
255 		i = 0;
256 		if ( si->si_allattrs == si->si_allopattrs ) {
257 			attrs = (char**) ch_malloc( 3 * sizeof(char*) );
258 			attrs[i++] = ch_strdup( "*" );
259 			attrs[i++] = ch_strdup( "+" );
260 		} else if ( si->si_allattrs && !si->si_allopattrs ) {
261 			for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
262 			attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
263 			attrs[i++] = ch_strdup( "*" );
264 			for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
265 				attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
266 			}
267 		} else if ( !si->si_allattrs && si->si_allopattrs ) {
268 			attrs = (char**) ch_malloc( 3 * sizeof(char*) );
269 			attrs[i++] = ch_strdup( "+" );
270 			attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
271 		}
272 		attrs[i] = NULL;
273 	}
274 
275 	si->si_attrs = attrs;
276 
277 	exattrs = anlist2attrs( si->si_exanlist );
278 
279 	if ( exattrs ) {
280 		for ( n = 0; exattrs[n] != NULL; n++ ) ;
281 
282 		for ( i = 0; sync_descs[i] != NULL; i++ ) {
283 			j = 0;
284 			while ( exattrs[j] != NULL ) {
285 				if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val ) ) {
286 					ch_free( exattrs[j] );
287 					for ( k = j; exattrs[k] != NULL; k++ ) {
288 						exattrs[k] = exattrs[k+1];
289 					}
290 				} else {
291 					j++;
292 				}
293 			}
294 		}
295 
296 		for ( i = 0; exattrs[i] != NULL; i++ ) {
297 			for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
298 				ObjectClass	*oc;
299 				if ( ( oc = si->si_anlist[j].an_oc ) ) {
300 					k = 0;
301 					while ( oc->soc_required[k] ) {
302 						if ( !strcmp( exattrs[i],
303 							 oc->soc_required[k]->sat_cname.bv_val ) ) {
304 							ch_free( exattrs[i] );
305 							for ( l = i; exattrs[l]; l++ ) {
306 								exattrs[l] = exattrs[l+1];
307 							}
308 						} else {
309 							k++;
310 						}
311 					}
312 				}
313 			}
314 		}
315 
316 		for ( i = 0; exattrs[i] != NULL; i++ ) ;
317 
318 		if ( i != n )
319 			exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *) );
320 	}
321 
322 	si->si_exattrs = exattrs;
323 }
324 
325 typedef struct logschema {
326 	struct berval ls_dn;
327 	struct berval ls_req;
328 	struct berval ls_mod;
329 	struct berval ls_newRdn;
330 	struct berval ls_delRdn;
331 	struct berval ls_newSup;
332 } logschema;
333 
334 static logschema changelog_sc = {
335 	BER_BVC("targetDN"),
336 	BER_BVC("changeType"),
337 	BER_BVC("changes"),
338 	BER_BVC("newRDN"),
339 	BER_BVC("deleteOldRDN"),
340 	BER_BVC("newSuperior")
341 };
342 
343 static logschema accesslog_sc = {
344 	BER_BVC("reqDN"),
345 	BER_BVC("reqType"),
346 	BER_BVC("reqMod"),
347 	BER_BVC("reqNewRDN"),
348 	BER_BVC("reqDeleteOldRDN"),
349 	BER_BVC("reqNewSuperior")
350 };
351 
352 static int
353 ldap_sync_search(
354 	syncinfo_t *si,
355 	void *ctx )
356 {
357 	BerElementBuffer berbuf;
358 	BerElement *ber = (BerElement *)&berbuf;
359 	LDAPControl c[3], *ctrls[4];
360 	int rc;
361 	int rhint;
362 	char *base;
363 	char **attrs, *lattrs[8];
364 	char *filter;
365 	int attrsonly;
366 	int scope;
367 
368 	/* setup LDAP SYNC control */
369 	ber_init2( ber, NULL, LBER_USE_DER );
370 	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
371 
372 	/* If we're using a log but we have no state, then fallback to
373 	 * normal mode for a full refresh.
374 	 */
375 	if ( si->si_syncdata && !si->si_syncCookie.numcsns ) {
376 		si->si_logstate = SYNCLOG_FALLBACK;
377 	}
378 
379 	/* Use the log parameters if we're in log mode */
380 	if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
381 		logschema *ls;
382 		if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
383 			ls = &accesslog_sc;
384 		else
385 			ls = &changelog_sc;
386 		lattrs[0] = ls->ls_dn.bv_val;
387 		lattrs[1] = ls->ls_req.bv_val;
388 		lattrs[2] = ls->ls_mod.bv_val;
389 		lattrs[3] = ls->ls_newRdn.bv_val;
390 		lattrs[4] = ls->ls_delRdn.bv_val;
391 		lattrs[5] = ls->ls_newSup.bv_val;
392 		lattrs[6] = slap_schema.si_ad_entryCSN->ad_cname.bv_val;
393 		lattrs[7] = NULL;
394 
395 		rhint = 0;
396 		base = si->si_logbase.bv_val;
397 		filter = si->si_logfilterstr.bv_val;
398 		attrs = lattrs;
399 		attrsonly = 0;
400 		scope = LDAP_SCOPE_SUBTREE;
401 	} else {
402 		rhint = 1;
403 		base = si->si_base.bv_val;
404 		filter = si->si_filterstr.bv_val;
405 		attrs = si->si_attrs;
406 		attrsonly = si->si_attrsonly;
407 		scope = si->si_scope;
408 	}
409 	if ( si->si_syncdata && si->si_logstate == SYNCLOG_FALLBACK ) {
410 		si->si_type = LDAP_SYNC_REFRESH_ONLY;
411 	} else {
412 		si->si_type = si->si_ctype;
413 	}
414 
415 	if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
416 	{
417 		ber_printf( ber, "{eOb}",
418 			abs(si->si_type), &si->si_syncCookie.octet_str, rhint );
419 	} else {
420 		ber_printf( ber, "{eb}",
421 			abs(si->si_type), rhint );
422 	}
423 
424 	if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 ) ) == -1 ) {
425 		ber_free_buf( ber );
426 		return rc;
427 	}
428 
429 	c[0].ldctl_oid = LDAP_CONTROL_SYNC;
430 	c[0].ldctl_iscritical = si->si_type < 0;
431 	ctrls[0] = &c[0];
432 
433 	c[1].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
434 	BER_BVZERO( &c[1].ldctl_value );
435 	c[1].ldctl_iscritical = 1;
436 	ctrls[1] = &c[1];
437 
438 	if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
439 		c[2].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
440 		c[2].ldctl_value = si->si_bindconf.sb_authzId;
441 		c[2].ldctl_iscritical = 1;
442 		ctrls[2] = &c[2];
443 		ctrls[3] = NULL;
444 	} else {
445 		ctrls[2] = NULL;
446 	}
447 
448 	rc = ldap_search_ext( si->si_ld, base, scope, filter, attrs, attrsonly,
449 		ctrls, NULL, NULL, si->si_slimit, &si->si_msgid );
450 	ber_free_buf( ber );
451 	return rc;
452 }
453 
454 static int
455 check_syncprov(
456 	Operation *op,
457 	syncinfo_t *si )
458 {
459 	AttributeName at[2];
460 	Attribute a = {0};
461 	Entry e = {0};
462 	SlapReply rs = {0};
463 	int i, j, changed = 0;
464 
465 	/* Look for contextCSN from syncprov overlay. If
466 	 * there's no overlay, this will be a no-op. That means
467 	 * this is a pure consumer, so local changes will not be
468 	 * allowed, and all changes will already be reflected in
469 	 * the cookieState.
470 	 */
471 	a.a_desc = slap_schema.si_ad_contextCSN;
472 	e.e_attrs = &a;
473 	e.e_name = si->si_contextdn;
474 	e.e_nname = si->si_contextdn;
475 	at[0].an_name = a.a_desc->ad_cname;
476 	at[0].an_desc = a.a_desc;
477 	BER_BVZERO( &at[1].an_name );
478 	rs.sr_entry = &e;
479 	rs.sr_flags = REP_ENTRY_MODIFIABLE;
480 	rs.sr_attrs = at;
481 	op->o_req_dn = e.e_name;
482 	op->o_req_ndn = e.e_nname;
483 
484 	ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
485 	i = backend_operational( op, &rs );
486 	if ( i == LDAP_SUCCESS && a.a_nvals ) {
487 		int num = a.a_numvals;
488 		/* check for differences */
489 		if ( num != si->si_cookieState->cs_num ) {
490 			changed = 1;
491 		} else {
492 			for ( i=0; i<num; i++ ) {
493 				if ( ber_bvcmp( &a.a_nvals[i],
494 					&si->si_cookieState->cs_vals[i] )) {
495 					changed = 1;
496 					break;
497 				}
498 			}
499 		}
500 		if ( changed ) {
501 			ber_bvarray_free( si->si_cookieState->cs_vals );
502 			ch_free( si->si_cookieState->cs_sids );
503 			si->si_cookieState->cs_num = num;
504 			si->si_cookieState->cs_vals = a.a_nvals;
505 			si->si_cookieState->cs_sids = slap_parse_csn_sids( a.a_nvals,
506 				num, NULL );
507 			si->si_cookieState->cs_age++;
508 		} else {
509 			ber_bvarray_free( a.a_nvals );
510 		}
511 		ber_bvarray_free( a.a_vals );
512 	}
513 	/* See if the cookieState has changed due to anything outside
514 	 * this particular consumer. That includes other consumers in
515 	 * the same context, or local changes detected above.
516 	 */
517 	if ( si->si_cookieState->cs_num > 0 && si->si_cookieAge !=
518 		si->si_cookieState->cs_age ) {
519 		if ( !si->si_syncCookie.numcsns ) {
520 			ber_bvarray_free( si->si_syncCookie.ctxcsn );
521 			ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
522 				si->si_cookieState->cs_vals, NULL );
523 			changed = 1;
524 		} else {
525 			for (i=0; !BER_BVISNULL( &si->si_syncCookie.ctxcsn[i] ); i++) {
526 				/* bogus, just dup everything */
527 				if ( si->si_syncCookie.sids[i] == -1 ) {
528 					ber_bvarray_free( si->si_syncCookie.ctxcsn );
529 					ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
530 						si->si_cookieState->cs_vals, NULL );
531 					changed = 1;
532 					break;
533 				}
534 				for (j=0; j<si->si_cookieState->cs_num; j++) {
535 					if ( si->si_syncCookie.sids[i] !=
536 						si->si_cookieState->cs_sids[j] )
537 						continue;
538 					if ( bvmatch( &si->si_syncCookie.ctxcsn[i],
539 						&si->si_cookieState->cs_vals[j] ))
540 						break;
541 					ber_bvreplace( &si->si_syncCookie.ctxcsn[i],
542 						&si->si_cookieState->cs_vals[j] );
543 					changed = 1;
544 					break;
545 				}
546 			}
547 		}
548 	}
549 	if ( changed ) {
550 		si->si_cookieAge = si->si_cookieState->cs_age;
551 		ch_free( si->si_syncCookie.octet_str.bv_val );
552 		slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
553 			si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
554 			si->si_syncCookie.sid );
555 	}
556 	ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
557 	return changed;
558 }
559 
560 static int
561 do_syncrep1(
562 	Operation *op,
563 	syncinfo_t *si )
564 {
565 	int	rc;
566 	int cmdline_cookie_found = 0;
567 
568 	struct sync_cookie	*sc = NULL;
569 #ifdef HAVE_TLS
570 	void	*ssl;
571 #endif
572 
573 	rc = slap_client_connect( &si->si_ld, &si->si_bindconf );
574 	if ( rc != LDAP_SUCCESS ) {
575 		goto done;
576 	}
577 	op->o_protocol = LDAP_VERSION3;
578 
579 	/* Set SSF to strongest of TLS, SASL SSFs */
580 	op->o_sasl_ssf = 0;
581 	op->o_tls_ssf = 0;
582 	op->o_transport_ssf = 0;
583 #ifdef HAVE_TLS
584 	if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
585 		== LDAP_SUCCESS && ssl != NULL )
586 	{
587 		op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
588 	}
589 #endif /* HAVE_TLS */
590 	{
591 		ber_len_t ssf; /* ITS#5403, 3864 LDAP_OPT_X_SASL_SSF probably ought
592 						  to use sasl_ssf_t but currently uses ber_len_t */
593 		if ( ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &ssf )
594 			== LDAP_SUCCESS )
595 			op->o_sasl_ssf = ssf;
596 	}
597 	op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
598 		?  op->o_sasl_ssf : op->o_tls_ssf;
599 
600 	ldap_set_option( si->si_ld, LDAP_OPT_TIMELIMIT, &si->si_tlimit );
601 
602 	rc = LDAP_DEREF_NEVER;	/* actually could allow DEREF_FINDING */
603 	ldap_set_option( si->si_ld, LDAP_OPT_DEREF, &rc );
604 
605 	ldap_set_option( si->si_ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF );
606 
607 	si->si_syncCookie.rid = si->si_rid;
608 
609 	/* whenever there are multiple data sources possible, advertise sid */
610 	si->si_syncCookie.sid = ( SLAP_MULTIMASTER( si->si_be ) || si->si_be != si->si_wbe ) ?
611 		slap_serverID : -1;
612 
613 	/* We've just started up, or the remote server hasn't sent us
614 	 * any meaningful state.
615 	 */
616 	if ( BER_BVISNULL( &si->si_syncCookie.octet_str ) ) {
617 		int i;
618 
619 		LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
620 			if ( si->si_rid == sc->rid ) {
621 				cmdline_cookie_found = 1;
622 				break;
623 			}
624 		}
625 
626 		if ( cmdline_cookie_found ) {
627 			/* cookie is supplied in the command line */
628 
629 			LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
630 
631 			/* ctxcsn wasn't parsed yet, do it now */
632 			slap_parse_sync_cookie( sc, op->o_tmpmemctx );
633 			slap_sync_cookie_free( &si->si_syncCookie, 0 );
634 			slap_dup_sync_cookie( &si->si_syncCookie, sc );
635 			slap_sync_cookie_free( sc, 1 );
636 		} else {
637 			ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
638 			if ( !si->si_cookieState->cs_num ) {
639 				/* get contextCSN shadow replica from database */
640 				BerVarray csn = NULL;
641 				void *ctx = op->o_tmpmemctx;
642 
643 				op->o_req_ndn = si->si_contextdn;
644 				op->o_req_dn = op->o_req_ndn;
645 
646 				/* try to read stored contextCSN */
647 				op->o_tmpmemctx = NULL;
648 				backend_attribute( op, NULL, &op->o_req_ndn,
649 					slap_schema.si_ad_contextCSN, &csn, ACL_READ );
650 				op->o_tmpmemctx = ctx;
651 				if ( csn ) {
652 					si->si_cookieState->cs_vals = csn;
653 					for (i=0; !BER_BVISNULL( &csn[i] ); i++);
654 					si->si_cookieState->cs_num = i;
655 					si->si_cookieState->cs_sids = slap_parse_csn_sids( csn, i, NULL );
656 				}
657 			}
658 			if ( si->si_cookieState->cs_num ) {
659 				ber_bvarray_free( si->si_syncCookie.ctxcsn );
660 				if ( ber_bvarray_dup_x( &si->si_syncCookie.ctxcsn,
661 					si->si_cookieState->cs_vals, NULL )) {
662 					rc = LDAP_NO_MEMORY;
663 					ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
664 					goto done;
665 				}
666 				si->si_syncCookie.numcsns = si->si_cookieState->cs_num;
667 				si->si_syncCookie.sids = ch_malloc( si->si_cookieState->cs_num *
668 					sizeof(int) );
669 				for ( i=0; i<si->si_syncCookie.numcsns; i++ )
670 					si->si_syncCookie.sids[i] = si->si_cookieState->cs_sids[i];
671 			}
672 			ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
673 		}
674 
675 		slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
676 			si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
677 			si->si_syncCookie.sid );
678 	} else {
679 		/* ITS#6367: recreate the cookie so it has our SID, not our peer's */
680 		ch_free( si->si_syncCookie.octet_str.bv_val );
681 		slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
682 			si->si_syncCookie.ctxcsn, si->si_syncCookie.rid,
683 			si->si_syncCookie.sid );
684 		/* Look for contextCSN from syncprov overlay. */
685 		check_syncprov( op, si );
686 	}
687 
688 	si->si_refreshDone = 0;
689 
690 	rc = ldap_sync_search( si, op->o_tmpmemctx );
691 
692 	if( rc != LDAP_SUCCESS ) {
693 		Debug( LDAP_DEBUG_ANY, "do_syncrep1: %s "
694 			"ldap_search_ext: %s (%d)\n",
695 			si->si_ridtxt, ldap_err2string( rc ), rc );
696 	}
697 
698 done:
699 	if ( rc ) {
700 		if ( si->si_ld ) {
701 			ldap_unbind_ext( si->si_ld, NULL, NULL );
702 			si->si_ld = NULL;
703 		}
704 	}
705 
706 	return rc;
707 }
708 
709 static int
710 compare_csns( struct sync_cookie *sc1, struct sync_cookie *sc2, int *which )
711 {
712 	int i, j, match = 0;
713 	const char *text;
714 
715 	*which = 0;
716 
717 	if ( sc1->numcsns < sc2->numcsns ) {
718 		*which = sc1->numcsns;
719 		return -1;
720 	}
721 
722 	for (j=0; j<sc2->numcsns; j++) {
723 		for (i=0; i<sc1->numcsns; i++) {
724 			if ( sc1->sids[i] != sc2->sids[j] )
725 				continue;
726 			value_match( &match, slap_schema.si_ad_entryCSN,
727 				slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
728 				SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
729 				&sc1->ctxcsn[i], &sc2->ctxcsn[j], &text );
730 			if ( match < 0 ) {
731 				*which = j;
732 				return match;
733 			}
734 			break;
735 		}
736 		if ( i == sc1->numcsns ) {
737 			/* sc2 has a sid sc1 lacks */
738 			*which = j;
739 			return -1;
740 		}
741 	}
742 	return match;
743 }
744 
745 #define	SYNC_PAUSED	-3
746 
747 static int
748 do_syncrep2(
749 	Operation *op,
750 	syncinfo_t *si )
751 {
752 	LDAPControl	**rctrls = NULL;
753 
754 	BerElementBuffer berbuf;
755 	BerElement	*ber = (BerElement *)&berbuf;
756 
757 	LDAPMessage	*msg = NULL;
758 
759 	char		*retoid = NULL;
760 	struct berval	*retdata = NULL;
761 
762 	Entry		*entry = NULL;
763 
764 	int		syncstate;
765 	struct berval	syncUUID = BER_BVNULL;
766 	struct sync_cookie	syncCookie = { NULL };
767 	struct sync_cookie	syncCookie_req = { NULL };
768 	struct berval		cookie = BER_BVNULL;
769 
770 	int		rc,
771 			err = LDAP_SUCCESS;
772 	ber_len_t	len;
773 
774 	Modifications	*modlist = NULL;
775 
776 	int				match, m, punlock = -1;
777 
778 	struct timeval *tout_p = NULL;
779 	struct timeval tout = { 0, 0 };
780 
781 	int		refreshDeletes = 0;
782 	BerVarray syncUUIDs = NULL;
783 	ber_tag_t si_tag;
784 
785 	if ( slapd_shutdown ) {
786 		rc = -2;
787 		goto done;
788 	}
789 
790 	ber_init2( ber, NULL, LBER_USE_DER );
791 	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
792 
793 	Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2 %s\n", si->si_ridtxt, 0, 0 );
794 
795 	slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
796 
797 	if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
798 		tout_p = &tout;
799 	} else {
800 		tout_p = NULL;
801 	}
802 
803 	while ( ( rc = ldap_result( si->si_ld, si->si_msgid, LDAP_MSG_ONE,
804 		tout_p, &msg ) ) > 0 )
805 	{
806 		LDAPControl	*rctrlp = NULL;
807 
808 		if ( slapd_shutdown ) {
809 			rc = -2;
810 			goto done;
811 		}
812 		switch( ldap_msgtype( msg ) ) {
813 		case LDAP_RES_SEARCH_ENTRY:
814 			ldap_get_entry_controls( si->si_ld, msg, &rctrls );
815 			/* we can't work without the control */
816 			if ( rctrls ) {
817 				LDAPControl **next = NULL;
818 				/* NOTE: make sure we use the right one;
819 				 * a better approach would be to run thru
820 				 * the whole list and take care of all */
821 				/* NOTE: since we issue the search request,
822 				 * we should know what controls to expect,
823 				 * and there should be none apart from the
824 				 * sync-related control */
825 				rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_STATE, rctrls, &next );
826 				if ( next && ldap_control_find( LDAP_CONTROL_SYNC_STATE, next, NULL ) )
827 				{
828 					Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
829 						"got search entry with multiple "
830 						"Sync State control\n", si->si_ridtxt, 0, 0 );
831 					ldap_controls_free( rctrls );
832 					rc = -1;
833 					goto done;
834 				}
835 			}
836 			if ( rctrlp == NULL ) {
837 				Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
838 					"got search entry without "
839 					"Sync State control\n", si->si_ridtxt, 0, 0 );
840 				rc = -1;
841 				goto done;
842 			}
843 			ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
844 			ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
845 			/* FIXME: what if syncUUID is NULL or empty?
846 			 * (happens with back-sql...) */
847 			if ( BER_BVISEMPTY( &syncUUID ) ) {
848 				Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
849 					"got empty syncUUID with LDAP_SYNC_%s\n",
850 					si->si_ridtxt,
851 					syncrepl_state2str( syncstate ), 0 );
852 				ldap_controls_free( rctrls );
853 				rc = -1;
854 				goto done;
855 			}
856 			if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
857 				ber_scanf( ber, /*"{"*/ "m}", &cookie );
858 
859 				Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
860 					si->si_ridtxt,
861 					BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
862 
863 				if ( !BER_BVISNULL( &cookie ) ) {
864 					ch_free( syncCookie.octet_str.bv_val );
865 					ber_dupbv( &syncCookie.octet_str, &cookie );
866 				}
867 				if ( !BER_BVISNULL( &syncCookie.octet_str ) )
868 				{
869 					slap_parse_sync_cookie( &syncCookie, NULL );
870 					if ( syncCookie.ctxcsn ) {
871 						int i, sid = slap_parse_csn_sid( syncCookie.ctxcsn );
872 						check_syncprov( op, si );
873 						for ( i =0; i<si->si_cookieState->cs_num; i++ ) {
874 							if ( si->si_cookieState->cs_sids[i] == sid ) {
875 								if ( ber_bvcmp( syncCookie.ctxcsn, &si->si_cookieState->cs_vals[i] ) <= 0 ) {
876 									Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN too old, ignoring %s\n",
877 										si->si_ridtxt, syncCookie.ctxcsn->bv_val, 0 );
878 									ldap_controls_free( rctrls );
879 									rc = 0;
880 									goto done;
881 								}
882 								break;
883 							}
884 						}
885 						/* check pending CSNs too */
886 						while ( ldap_pvt_thread_mutex_trylock( &si->si_cookieState->cs_pmutex )) {
887 							if ( slapd_shutdown ) {
888 								rc = -2;
889 								goto done;
890 							}
891 							if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
892 								ldap_pvt_thread_yield();
893 						}
894 						for ( i =0; i<si->si_cookieState->cs_pnum; i++ ) {
895 							if ( si->si_cookieState->cs_psids[i] == sid ) {
896 								if ( ber_bvcmp( syncCookie.ctxcsn, &si->si_cookieState->cs_pvals[i] ) <= 0 ) {
897 									Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s CSN pending, ignoring %s\n",
898 										si->si_ridtxt, syncCookie.ctxcsn->bv_val, 0 );
899 									ldap_controls_free( rctrls );
900 									rc = 0;
901 									ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_pmutex );
902 									goto done;
903 								}
904 								ber_bvreplace( &si->si_cookieState->cs_pvals[i],
905 									syncCookie.ctxcsn );
906 								break;
907 							}
908 						}
909 						/* new SID, add it */
910 						if ( i == si->si_cookieState->cs_pnum ) {
911 							value_add( &si->si_cookieState->cs_pvals, syncCookie.ctxcsn );
912 							si->si_cookieState->cs_pnum++;
913 							si->si_cookieState->cs_psids = ch_realloc( si->si_cookieState->cs_psids, si->si_cookieState->cs_pnum * sizeof(int));
914 							si->si_cookieState->cs_psids[i] = sid;
915 						}
916 						punlock = i;
917 					}
918 					op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
919 				}
920 			}
921 			rc = 0;
922 			if ( si->si_syncdata && si->si_logstate == SYNCLOG_LOGGING ) {
923 				modlist = NULL;
924 				if ( ( rc = syncrepl_message_to_op( si, op, msg ) ) == LDAP_SUCCESS &&
925 					syncCookie.ctxcsn )
926 				{
927 					rc = syncrepl_updateCookie( si, op, &syncCookie );
928 				} else switch ( rc ) {
929 					case LDAP_ALREADY_EXISTS:
930 					case LDAP_NO_SUCH_OBJECT:
931 					case LDAP_NO_SUCH_ATTRIBUTE:
932 					case LDAP_TYPE_OR_VALUE_EXISTS:
933 						rc = LDAP_SYNC_REFRESH_REQUIRED;
934 						si->si_logstate = SYNCLOG_FALLBACK;
935 						ldap_abandon_ext( si->si_ld, si->si_msgid, NULL, NULL );
936 						break;
937 					default:
938 						break;
939 				}
940 			} else if ( ( rc = syncrepl_message_to_entry( si, op, msg,
941 				&modlist, &entry, syncstate ) ) == LDAP_SUCCESS )
942 			{
943 				if ( ( rc = syncrepl_entry( si, op, entry, &modlist,
944 					syncstate, &syncUUID, syncCookie.ctxcsn ) ) == LDAP_SUCCESS &&
945 					syncCookie.ctxcsn )
946 				{
947 					rc = syncrepl_updateCookie( si, op, &syncCookie );
948 				}
949 			}
950 			if ( punlock >= 0 ) {
951 				/* on failure, revert pending CSN */
952 				if ( rc != LDAP_SUCCESS ) {
953 					int i;
954 					for ( i = 0; i<si->si_cookieState->cs_num; i++ ) {
955 						if ( si->si_cookieState->cs_sids[i] == si->si_cookieState->cs_psids[punlock] ) {
956 							ber_bvreplace( &si->si_cookieState->cs_pvals[punlock],
957 								&si->si_cookieState->cs_vals[i] );
958 							break;
959 						}
960 					}
961 					if ( i == si->si_cookieState->cs_num )
962 						si->si_cookieState->cs_pvals[punlock].bv_val[0] = '\0';
963 				}
964 				ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_pmutex );
965 			}
966 			ldap_controls_free( rctrls );
967 			if ( modlist ) {
968 				slap_mods_free( modlist, 1 );
969 			}
970 			if ( rc )
971 				goto done;
972 			break;
973 
974 		case LDAP_RES_SEARCH_REFERENCE:
975 			Debug( LDAP_DEBUG_ANY,
976 				"do_syncrep2: %s reference received error\n",
977 				si->si_ridtxt, 0, 0 );
978 			break;
979 
980 		case LDAP_RES_SEARCH_RESULT:
981 			Debug( LDAP_DEBUG_SYNC,
982 				"do_syncrep2: %s LDAP_RES_SEARCH_RESULT\n",
983 				si->si_ridtxt, 0, 0 );
984 			ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
985 				&rctrls, 0 );
986 #ifdef LDAP_X_SYNC_REFRESH_REQUIRED
987 			if ( err == LDAP_X_SYNC_REFRESH_REQUIRED ) {
988 				/* map old result code to registered code */
989 				err = LDAP_SYNC_REFRESH_REQUIRED;
990 			}
991 #endif
992 			if ( err == LDAP_SYNC_REFRESH_REQUIRED ) {
993 				if ( si->si_logstate == SYNCLOG_LOGGING ) {
994 					si->si_logstate = SYNCLOG_FALLBACK;
995 				}
996 				rc = err;
997 				goto done;
998 			}
999 			if ( err ) {
1000 				Debug( LDAP_DEBUG_ANY,
1001 					"do_syncrep2: %s LDAP_RES_SEARCH_RESULT (%d) %s\n",
1002 					si->si_ridtxt, err, ldap_err2string( err ) );
1003 			}
1004 			if ( rctrls ) {
1005 				LDAPControl **next = NULL;
1006 				/* NOTE: make sure we use the right one;
1007 				 * a better approach would be to run thru
1008 				 * the whole list and take care of all */
1009 				/* NOTE: since we issue the search request,
1010 				 * we should know what controls to expect,
1011 				 * and there should be none apart from the
1012 				 * sync-related control */
1013 				rctrlp = ldap_control_find( LDAP_CONTROL_SYNC_DONE, rctrls, &next );
1014 				if ( next && ldap_control_find( LDAP_CONTROL_SYNC_DONE, next, NULL ) )
1015 				{
1016 					Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1017 						"got search result with multiple "
1018 						"Sync State control\n", si->si_ridtxt, 0, 0 );
1019 					ldap_controls_free( rctrls );
1020 					rc = -1;
1021 					goto done;
1022 				}
1023 			}
1024 			if ( rctrlp ) {
1025 				ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
1026 
1027 				ber_scanf( ber, "{" /*"}"*/);
1028 				if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
1029 					ber_scanf( ber, "m", &cookie );
1030 
1031 					Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1032 						si->si_ridtxt,
1033 						BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1034 
1035 					if ( !BER_BVISNULL( &cookie ) ) {
1036 						ch_free( syncCookie.octet_str.bv_val );
1037 						ber_dupbv( &syncCookie.octet_str, &cookie);
1038 					}
1039 					if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1040 					{
1041 						slap_parse_sync_cookie( &syncCookie, NULL );
1042 						op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1043 					}
1044 				}
1045 				if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
1046 				{
1047 					ber_scanf( ber, "b", &refreshDeletes );
1048 				}
1049 				ber_scanf( ber, /*"{"*/ "}" );
1050 			}
1051 			if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
1052 				slap_sync_cookie_free( &syncCookie_req, 0 );
1053 				slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
1054 			}
1055 			if ( !syncCookie.ctxcsn ) {
1056 				match = 1;
1057 			} else if ( !syncCookie_req.ctxcsn ) {
1058 				match = -1;
1059 				m = 0;
1060 			} else {
1061 				match = compare_csns( &syncCookie_req, &syncCookie, &m );
1062 			}
1063 			if ( rctrls ) {
1064 				ldap_controls_free( rctrls );
1065 			}
1066 			if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
1067 				/* FIXME : different error behaviors according to
1068 				 *	1) err code : LDAP_BUSY ...
1069 				 *	2) on err policy : stop service, stop sync, retry
1070 				 */
1071 				if ( refreshDeletes == 0 && match < 0 &&
1072 					err == LDAP_SUCCESS &&
1073 					syncCookie_req.numcsns == syncCookie.numcsns )
1074 				{
1075 					syncrepl_del_nonpresent( op, si, NULL,
1076 						&syncCookie, m );
1077 				} else {
1078 					avl_free( si->si_presentlist, ch_free );
1079 					si->si_presentlist = NULL;
1080 				}
1081 			}
1082 			if ( syncCookie.ctxcsn && match < 0 && err == LDAP_SUCCESS )
1083 			{
1084 				rc = syncrepl_updateCookie( si, op, &syncCookie );
1085 			}
1086 			if ( err == LDAP_SUCCESS
1087 				&& si->si_logstate == SYNCLOG_FALLBACK ) {
1088 				si->si_logstate = SYNCLOG_LOGGING;
1089 				rc = LDAP_SYNC_REFRESH_REQUIRED;
1090 			} else {
1091 				rc = -2;
1092 			}
1093 			goto done;
1094 			break;
1095 
1096 		case LDAP_RES_INTERMEDIATE:
1097 			rc = ldap_parse_intermediate( si->si_ld, msg,
1098 				&retoid, &retdata, NULL, 0 );
1099 			if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
1100 				ber_init2( ber, retdata, LBER_USE_DER );
1101 
1102 				switch ( si_tag = ber_peek_tag( ber, &len ) ) {
1103 				ber_tag_t tag;
1104 				case LDAP_TAG_SYNC_NEW_COOKIE:
1105 					Debug( LDAP_DEBUG_SYNC,
1106 						"do_syncrep2: %s %s - %s\n",
1107 						si->si_ridtxt,
1108 						"LDAP_RES_INTERMEDIATE",
1109 						"NEW_COOKIE" );
1110 					ber_scanf( ber, "tm", &tag, &cookie );
1111 					Debug( LDAP_DEBUG_SYNC,
1112 						"do_syncrep2: %s NEW_COOKIE: %s\n",
1113 						si->si_ridtxt,
1114 						cookie.bv_val, 0);
1115 					if ( !BER_BVISNULL( &cookie ) ) {
1116 						ch_free( syncCookie.octet_str.bv_val );
1117 						ber_dupbv( &syncCookie.octet_str, &cookie );
1118 					}
1119 					if (!BER_BVISNULL( &syncCookie.octet_str ) ) {
1120 						slap_parse_sync_cookie( &syncCookie, NULL );
1121 						op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1122 					}
1123 					break;
1124 				case LDAP_TAG_SYNC_REFRESH_DELETE:
1125 				case LDAP_TAG_SYNC_REFRESH_PRESENT:
1126 					Debug( LDAP_DEBUG_SYNC,
1127 						"do_syncrep2: %s %s - %s\n",
1128 						si->si_ridtxt,
1129 						"LDAP_RES_INTERMEDIATE",
1130 						si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
1131 						"REFRESH_PRESENT" : "REFRESH_DELETE" );
1132 					if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
1133 						si->si_refreshDelete = 1;
1134 					} else {
1135 						si->si_refreshPresent = 1;
1136 					}
1137 					ber_scanf( ber, "t{" /*"}"*/, &tag );
1138 					if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
1139 					{
1140 						ber_scanf( ber, "m", &cookie );
1141 
1142 						Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1143 							si->si_ridtxt,
1144 							BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1145 
1146 						if ( !BER_BVISNULL( &cookie ) ) {
1147 							ch_free( syncCookie.octet_str.bv_val );
1148 							ber_dupbv( &syncCookie.octet_str, &cookie );
1149 						}
1150 						if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1151 						{
1152 							slap_parse_sync_cookie( &syncCookie, NULL );
1153 							op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1154 						}
1155 					}
1156 					/* Defaults to TRUE */
1157 					if ( ber_peek_tag( ber, &len ) ==
1158 						LDAP_TAG_REFRESHDONE )
1159 					{
1160 						ber_scanf( ber, "b", &si->si_refreshDone );
1161 					} else
1162 					{
1163 						si->si_refreshDone = 1;
1164 					}
1165 					ber_scanf( ber, /*"{"*/ "}" );
1166 					break;
1167 				case LDAP_TAG_SYNC_ID_SET:
1168 					Debug( LDAP_DEBUG_SYNC,
1169 						"do_syncrep2: %s %s - %s\n",
1170 						si->si_ridtxt,
1171 						"LDAP_RES_INTERMEDIATE",
1172 						"SYNC_ID_SET" );
1173 					ber_scanf( ber, "t{" /*"}"*/, &tag );
1174 					if ( ber_peek_tag( ber, &len ) ==
1175 						LDAP_TAG_SYNC_COOKIE )
1176 					{
1177 						ber_scanf( ber, "m", &cookie );
1178 
1179 						Debug( LDAP_DEBUG_SYNC, "do_syncrep2: %s cookie=%s\n",
1180 							si->si_ridtxt,
1181 							BER_BVISNULL( &cookie ) ? "" : cookie.bv_val, 0 );
1182 
1183 						if ( !BER_BVISNULL( &cookie ) ) {
1184 							ch_free( syncCookie.octet_str.bv_val );
1185 							ber_dupbv( &syncCookie.octet_str, &cookie );
1186 						}
1187 						if ( !BER_BVISNULL( &syncCookie.octet_str ) )
1188 						{
1189 							slap_parse_sync_cookie( &syncCookie, NULL );
1190 							op->o_controls[slap_cids.sc_LDAPsync] = &syncCookie;
1191 							compare_csns( &syncCookie_req, &syncCookie, &m );
1192 						}
1193 					}
1194 					if ( ber_peek_tag( ber, &len ) ==
1195 						LDAP_TAG_REFRESHDELETES )
1196 					{
1197 						ber_scanf( ber, "b", &refreshDeletes );
1198 					}
1199 					ber_scanf( ber, "[W]", &syncUUIDs );
1200 					ber_scanf( ber, /*"{"*/ "}" );
1201 					if ( refreshDeletes ) {
1202 						syncrepl_del_nonpresent( op, si, syncUUIDs,
1203 							&syncCookie, m );
1204 						ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
1205 					} else {
1206 						int i;
1207 						for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
1208 							(void)avl_presentlist_insert( si, &syncUUIDs[i] );
1209 							slap_sl_free( syncUUIDs[i].bv_val, op->o_tmpmemctx );
1210 						}
1211 						slap_sl_free( syncUUIDs, op->o_tmpmemctx );
1212 					}
1213 					slap_sync_cookie_free( &syncCookie, 0 );
1214 					break;
1215 				default:
1216 					Debug( LDAP_DEBUG_ANY,
1217 						"do_syncrep2: %s unknown syncinfo tag (%ld)\n",
1218 						si->si_ridtxt, (long) si_tag, 0 );
1219 					ldap_memfree( retoid );
1220 					ber_bvfree( retdata );
1221 					continue;
1222 				}
1223 
1224 				if ( SLAP_MULTIMASTER( op->o_bd ) && check_syncprov( op, si )) {
1225 					slap_sync_cookie_free( &syncCookie_req, 0 );
1226 					slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
1227 				}
1228 				if ( !syncCookie.ctxcsn ) {
1229 					match = 1;
1230 				} else if ( !syncCookie_req.ctxcsn ) {
1231 					match = -1;
1232 					m = 0;
1233 				} else {
1234 					match = compare_csns( &syncCookie_req, &syncCookie, &m );
1235 				}
1236 
1237 				if ( match < 0 ) {
1238 					if ( si->si_refreshPresent == 1 &&
1239 						si_tag != LDAP_TAG_SYNC_NEW_COOKIE &&
1240 						syncCookie_req.numcsns == syncCookie.numcsns ) {
1241 						syncrepl_del_nonpresent( op, si, NULL,
1242 							&syncCookie, m );
1243 					}
1244 
1245 					if ( syncCookie.ctxcsn )
1246 					{
1247 						rc = syncrepl_updateCookie( si, op, &syncCookie);
1248 					}
1249 				}
1250 
1251 				ldap_memfree( retoid );
1252 				ber_bvfree( retdata );
1253 				break;
1254 
1255 			} else {
1256 				Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1257 					"unknown intermediate response (%d)\n",
1258 					si->si_ridtxt, rc, 0 );
1259 				ldap_memfree( retoid );
1260 				ber_bvfree( retdata );
1261 				break;
1262 			}
1263 			break;
1264 
1265 		default:
1266 			Debug( LDAP_DEBUG_ANY, "do_syncrep2: %s "
1267 				"unknown message (0x%02lx)\n",
1268 				si->si_ridtxt,
1269 				(unsigned long)ldap_msgtype( msg ), 0 );
1270 			break;
1271 
1272 		}
1273 		if ( !BER_BVISNULL( &syncCookie.octet_str ) ) {
1274 			slap_sync_cookie_free( &syncCookie_req, 0 );
1275 			slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
1276 			slap_sync_cookie_free( &syncCookie, 0 );
1277 		}
1278 		ldap_msgfree( msg );
1279 		msg = NULL;
1280 		if ( ldap_pvt_thread_pool_pausing( &connection_pool )) {
1281 			slap_sync_cookie_free( &syncCookie, 0 );
1282 			slap_sync_cookie_free( &syncCookie_req, 0 );
1283 			return SYNC_PAUSED;
1284 		}
1285 	}
1286 
1287 	if ( rc == -1 ) {
1288 		ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
1289 		err = rc;
1290 	}
1291 
1292 done:
1293 	if ( err != LDAP_SUCCESS ) {
1294 		Debug( LDAP_DEBUG_ANY,
1295 			"do_syncrep2: %s (%d) %s\n",
1296 			si->si_ridtxt, err, ldap_err2string( err ) );
1297 	}
1298 
1299 	slap_sync_cookie_free( &syncCookie, 0 );
1300 	slap_sync_cookie_free( &syncCookie_req, 0 );
1301 
1302 	if ( msg ) ldap_msgfree( msg );
1303 
1304 	if ( rc && rc != LDAP_SYNC_REFRESH_REQUIRED && si->si_ld ) {
1305 		if ( si->si_conn ) {
1306 			connection_client_stop( si->si_conn );
1307 			si->si_conn = NULL;
1308 		}
1309 		ldap_unbind_ext( si->si_ld, NULL, NULL );
1310 		si->si_ld = NULL;
1311 	}
1312 
1313 	return rc;
1314 }
1315 
1316 static void *
1317 do_syncrepl(
1318 	void	*ctx,
1319 	void	*arg )
1320 {
1321 	struct re_s* rtask = arg;
1322 	syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
1323 	Connection conn = {0};
1324 	OperationBuffer opbuf;
1325 	Operation *op;
1326 	int rc = LDAP_SUCCESS;
1327 	int dostop = 0;
1328 	ber_socket_t s;
1329 	int i, defer = 1, fail = 0, freeinfo = 0;
1330 	Backend *be;
1331 
1332 	if ( si == NULL )
1333 		return NULL;
1334 	if ( slapd_shutdown )
1335 		return NULL;
1336 
1337 	Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl %s\n", si->si_ridtxt, 0, 0 );
1338 
1339 	/* Don't get stuck here while a pause is initiated */
1340 	while ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
1341 		if ( slapd_shutdown )
1342 			return NULL;
1343 		if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
1344 			ldap_pvt_thread_yield();
1345 	}
1346 
1347 	if ( si->si_ctype < 1 ) {
1348 		goto deleted;
1349 	}
1350 
1351 	switch( abs( si->si_type ) ) {
1352 	case LDAP_SYNC_REFRESH_ONLY:
1353 	case LDAP_SYNC_REFRESH_AND_PERSIST:
1354 		break;
1355 	default:
1356 		ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1357 		return NULL;
1358 	}
1359 
1360 	if ( slapd_shutdown ) {
1361 		if ( si->si_ld ) {
1362 			if ( si->si_conn ) {
1363 				connection_client_stop( si->si_conn );
1364 				si->si_conn = NULL;
1365 			}
1366 			ldap_unbind_ext( si->si_ld, NULL, NULL );
1367 			si->si_ld = NULL;
1368 		}
1369 		ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1370 		return NULL;
1371 	}
1372 
1373 	connection_fake_init( &conn, &opbuf, ctx );
1374 	op = &opbuf.ob_op;
1375 	/* o_connids must be unique for slap_graduate_commit_csn */
1376 	op->o_connid = SLAPD_SYNC_RID2SYNCCONN(si->si_rid);
1377 
1378 	op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1379 	be = si->si_be;
1380 
1381 	/* Coordinate contextCSN updates with any syncprov overlays
1382 	 * in use. This may be complicated by the use of the glue
1383 	 * overlay.
1384 	 *
1385 	 * Typically there is a single syncprov mastering the entire
1386 	 * glued tree. In that case, our contextCSN updates should
1387 	 * go to the master DB. But if there is no syncprov on the
1388 	 * master DB, then nothing special is needed here.
1389 	 *
1390 	 * Alternatively, there may be individual syncprov overlays
1391 	 * on each glued branch. In that case, each syncprov only
1392 	 * knows about changes within its own branch. And so our
1393 	 * contextCSN updates should only go to the local DB.
1394 	 */
1395 	if ( !si->si_wbe ) {
1396 		if ( SLAP_GLUE_SUBORDINATE( be ) && !overlay_is_inst( be, "syncprov" )) {
1397 			BackendDB * top_be = select_backend( &be->be_nsuffix[0], 1 );
1398 			if ( overlay_is_inst( top_be, "syncprov" ))
1399 				si->si_wbe = top_be;
1400 			else
1401 				si->si_wbe = be;
1402 		} else {
1403 			si->si_wbe = be;
1404 		}
1405 		if ( SLAP_SYNC_SUBENTRY( si->si_wbe )) {
1406 			build_new_dn( &si->si_contextdn, &si->si_wbe->be_nsuffix[0],
1407 				(struct berval *)&slap_ldapsync_cn_bv, NULL );
1408 		} else {
1409 			si->si_contextdn = si->si_wbe->be_nsuffix[0];
1410 		}
1411 	}
1412 	if ( !si->si_schemachecking )
1413 		op->o_no_schema_check = 1;
1414 
1415 	/* Establish session, do search */
1416 	if ( !si->si_ld ) {
1417 		si->si_refreshDelete = 0;
1418 		si->si_refreshPresent = 0;
1419 
1420 		/* use main DB when retrieving contextCSN */
1421 		op->o_bd = si->si_wbe;
1422 		op->o_dn = op->o_bd->be_rootdn;
1423 		op->o_ndn = op->o_bd->be_rootndn;
1424 		rc = do_syncrep1( op, si );
1425 	}
1426 
1427 reload:
1428 	/* Process results */
1429 	if ( rc == LDAP_SUCCESS ) {
1430 		ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1431 
1432 		/* use current DB */
1433 		op->o_bd = be;
1434 		op->o_dn = op->o_bd->be_rootdn;
1435 		op->o_ndn = op->o_bd->be_rootndn;
1436 		rc = do_syncrep2( op, si );
1437 		if ( rc == LDAP_SYNC_REFRESH_REQUIRED )	{
1438 			rc = ldap_sync_search( si, op->o_tmpmemctx );
1439 			goto reload;
1440 		}
1441 
1442 deleted:
1443 		/* We got deleted while running on cn=config */
1444 		if ( si->si_ctype < 1 ) {
1445 			if ( si->si_ctype == -1 ) {
1446 				si->si_ctype = 0;
1447 				freeinfo = 1;
1448 			}
1449 			if ( si->si_conn )
1450 				dostop = 1;
1451 			rc = -1;
1452 		}
1453 
1454 		if ( rc != SYNC_PAUSED ) {
1455 			if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1456 				/* If we succeeded, enable the connection for further listening.
1457 				 * If we failed, tear down the connection and reschedule.
1458 				 */
1459 				if ( rc == LDAP_SUCCESS ) {
1460 					if ( si->si_conn ) {
1461 						connection_client_enable( si->si_conn );
1462 					} else {
1463 						si->si_conn = connection_client_setup( s, do_syncrepl, arg );
1464 					}
1465 				} else if ( si->si_conn ) {
1466 					dostop = 1;
1467 				}
1468 			} else {
1469 				if ( rc == -2 ) rc = 0;
1470 			}
1471 		}
1472 	}
1473 
1474 	/* At this point, we have 5 cases:
1475 	 * 1) for any hard failure, give up and remove this task
1476 	 * 2) for ServerDown, reschedule this task to run later
1477 	 * 3) for threadpool pause, reschedule to run immediately
1478 	 * 4) for Refresh and Success, reschedule to run
1479 	 * 5) for Persist and Success, reschedule to defer
1480 	 */
1481 	ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1482 
1483 	if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask ) ) {
1484 		ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1485 	}
1486 
1487 	if ( dostop ) {
1488 		connection_client_stop( si->si_conn );
1489 		si->si_conn = NULL;
1490 	}
1491 
1492 	if ( rc == SYNC_PAUSED ) {
1493 		rtask->interval.tv_sec = 0;
1494 		ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1495 		rtask->interval.tv_sec = si->si_interval;
1496 		rc = 0;
1497 	} else if ( rc == LDAP_SUCCESS ) {
1498 		if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1499 			defer = 0;
1500 		}
1501 		rtask->interval.tv_sec = si->si_interval;
1502 		ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1503 		if ( si->si_retrynum ) {
1504 			for ( i = 0; si->si_retrynum_init[i] != RETRYNUM_TAIL; i++ ) {
1505 				si->si_retrynum[i] = si->si_retrynum_init[i];
1506 			}
1507 			si->si_retrynum[i] = RETRYNUM_TAIL;
1508 		}
1509 	} else {
1510 		for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1511 			if ( si->si_retrynum[i] == RETRYNUM_FOREVER || si->si_retrynum[i] == RETRYNUM_TAIL )
1512 				break;
1513 		}
1514 
1515 		if ( si->si_ctype < 1
1516 			|| !si->si_retrynum || si->si_retrynum[i] == RETRYNUM_TAIL ) {
1517 			if ( si->si_re ) {
1518 				ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1519 				si->si_re = NULL;
1520 			}
1521 			fail = RETRYNUM_TAIL;
1522 		} else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1523 			if ( si->si_retrynum[i] > 0 )
1524 				si->si_retrynum[i]--;
1525 			fail = si->si_retrynum[i];
1526 			rtask->interval.tv_sec = si->si_retryinterval[i];
1527 			ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1528 			slap_wake_listener();
1529 		}
1530 	}
1531 
1532 	ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1533 	ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1534 
1535 	if ( rc ) {
1536 		if ( fail == RETRYNUM_TAIL ) {
1537 			Debug( LDAP_DEBUG_ANY,
1538 				"do_syncrepl: %s rc %d quitting\n",
1539 				si->si_ridtxt, rc, 0 );
1540 		} else if ( fail > 0 ) {
1541 			Debug( LDAP_DEBUG_ANY,
1542 				"do_syncrepl: %s rc %d retrying (%d retries left)\n",
1543 				si->si_ridtxt, rc, fail );
1544 		} else {
1545 			Debug( LDAP_DEBUG_ANY,
1546 				"do_syncrepl: %s rc %d retrying\n",
1547 				si->si_ridtxt, rc, 0 );
1548 		}
1549 	}
1550 
1551 	/* Do final delete cleanup */
1552 	if ( freeinfo ) {
1553 		syncinfo_free( si, 0 );
1554 	}
1555 	return NULL;
1556 }
1557 
1558 static slap_verbmasks modops[] = {
1559 	{ BER_BVC("add"), LDAP_REQ_ADD },
1560 	{ BER_BVC("delete"), LDAP_REQ_DELETE },
1561 	{ BER_BVC("modify"), LDAP_REQ_MODIFY },
1562 	{ BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1563 	{ BER_BVNULL, 0 }
1564 };
1565 
1566 static int
1567 syncrepl_accesslog_mods(
1568 	syncinfo_t *si,
1569 	struct berval *vals,
1570 	struct Modifications **modres
1571 )
1572 {
1573 	char *colon;
1574 	const char *text;
1575 	AttributeDescription *ad;
1576 	struct berval bv, bv2;
1577 	short op;
1578 	Modifications *mod = NULL, *modlist = NULL, **modtail;
1579 	int i, rc = 0;
1580 
1581 	modtail = &modlist;
1582 
1583 	for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1584 		ad = NULL;
1585 		bv = vals[i];
1586 
1587 		colon = ber_bvchr( &bv, ':' );
1588 		if ( !colon ) {
1589 			/* Invalid */
1590 			continue;
1591 		}
1592 
1593 		bv.bv_len = colon - bv.bv_val;
1594 		if ( slap_bv2ad( &bv, &ad, &text ) ) {
1595 			/* Invalid */
1596 			Debug( LDAP_DEBUG_ANY, "syncrepl_accesslog_mods: %s "
1597 				"Invalid attribute %s, %s\n",
1598 				si->si_ridtxt, bv.bv_val, text );
1599 			slap_mods_free( modlist, 1 );
1600 			modlist = NULL;
1601 			rc = -1;
1602 			break;
1603 		}
1604 
1605 		/* Ignore dynamically generated attrs */
1606 		if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1607 			continue;
1608 		}
1609 
1610 		/* Ignore excluded attrs */
1611 		if ( ldap_charray_inlist( si->si_exattrs,
1612 			ad->ad_type->sat_cname.bv_val ) )
1613 		{
1614 			continue;
1615 		}
1616 
1617 		switch(colon[1]) {
1618 		case '+':	op = LDAP_MOD_ADD; break;
1619 		case '-':	op = LDAP_MOD_DELETE; break;
1620 		case '=':	op = LDAP_MOD_REPLACE; break;
1621 		case '#':	op = LDAP_MOD_INCREMENT; break;
1622 		default:	continue;
1623 		}
1624 
1625 		if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1626 			mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
1627 			mod->sml_flags = 0;
1628 			mod->sml_op = op;
1629 			mod->sml_next = NULL;
1630 			mod->sml_desc = ad;
1631 			mod->sml_type = ad->ad_cname;
1632 			mod->sml_values = NULL;
1633 			mod->sml_nvalues = NULL;
1634 			mod->sml_numvals = 0;
1635 
1636 			*modtail = mod;
1637 			modtail = &mod->sml_next;
1638 		}
1639 		if ( colon[2] == ' ' ) {
1640 			bv.bv_val = colon + 3;
1641 			bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1642 			ber_dupbv( &bv2, &bv );
1643 			ber_bvarray_add( &mod->sml_values, &bv2 );
1644 			mod->sml_numvals++;
1645 		}
1646 	}
1647 	*modres = modlist;
1648 	return rc;
1649 }
1650 
1651 static int
1652 syncrepl_changelog_mods(
1653 	syncinfo_t *si,
1654 	struct berval *vals,
1655 	struct Modifications **modres
1656 )
1657 {
1658 	return -1;	/* FIXME */
1659 }
1660 
1661 static int
1662 syncrepl_message_to_op(
1663 	syncinfo_t	*si,
1664 	Operation	*op,
1665 	LDAPMessage	*msg
1666 )
1667 {
1668 	BerElement	*ber = NULL;
1669 	Modifications	*modlist = NULL;
1670 	logschema *ls;
1671 	SlapReply rs = { REP_RESULT };
1672 	slap_callback cb = { NULL, null_callback, NULL, NULL };
1673 
1674 	const char	*text;
1675 	char txtbuf[SLAP_TEXT_BUFLEN];
1676 	size_t textlen = sizeof txtbuf;
1677 
1678 	struct berval	bdn, dn = BER_BVNULL, ndn;
1679 	struct berval	bv, *bvals = NULL;
1680 	struct berval	rdn = BER_BVNULL, sup = BER_BVNULL,
1681 		prdn = BER_BVNULL, nrdn = BER_BVNULL,
1682 		psup = BER_BVNULL, nsup = BER_BVNULL;
1683 	int		rc, deleteOldRdn = 0, freeReqDn = 0;
1684 	int		do_graduate = 0;
1685 
1686 	if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1687 		Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1688 			"Message type should be entry (%d)",
1689 			si->si_ridtxt, ldap_msgtype( msg ), 0 );
1690 		return -1;
1691 	}
1692 
1693 	if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1694 		ls = &accesslog_sc;
1695 	else
1696 		ls = &changelog_sc;
1697 
1698 	rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1699 
1700 	if ( rc != LDAP_SUCCESS ) {
1701 		Debug( LDAP_DEBUG_ANY,
1702 			"syncrepl_message_to_op: %s dn get failed (%d)",
1703 			si->si_ridtxt, rc, 0 );
1704 		return rc;
1705 	}
1706 
1707 	op->o_tag = LBER_DEFAULT;
1708 	op->o_bd = si->si_wbe;
1709 
1710 	if ( BER_BVISEMPTY( &bdn ) && !BER_BVISEMPTY( &op->o_bd->be_nsuffix[0] ) ) {
1711 		Debug( LDAP_DEBUG_ANY,
1712 			"syncrepl_message_to_op: %s got empty dn",
1713 			si->si_ridtxt, 0, 0 );
1714 		return LDAP_OTHER;
1715 	}
1716 
1717 	while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ) )
1718 		== LDAP_SUCCESS ) {
1719 		if ( bv.bv_val == NULL )
1720 			break;
1721 
1722 		if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn ) ) {
1723 			bdn = bvals[0];
1724 			rc = dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1725 			if ( rc != LDAP_SUCCESS ) {
1726 				Debug( LDAP_DEBUG_ANY,
1727 					"syncrepl_message_to_op: %s "
1728 					"dn \"%s\" normalization failed (%d)",
1729 					si->si_ridtxt, bdn.bv_val, rc );
1730 				rc = -1;
1731 				ch_free( bvals );
1732 				goto done;
1733 			}
1734 			ber_dupbv( &op->o_req_dn, &dn );
1735 			ber_dupbv( &op->o_req_ndn, &ndn );
1736 			slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1737 			slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1738 			freeReqDn = 1;
1739 		} else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req ) ) {
1740 			int i = verb_to_mask( bvals[0].bv_val, modops );
1741 			if ( i < 0 ) {
1742 				Debug( LDAP_DEBUG_ANY,
1743 					"syncrepl_message_to_op: %s unknown op %s",
1744 					si->si_ridtxt, bvals[0].bv_val, 0 );
1745 				ch_free( bvals );
1746 				rc = -1;
1747 				goto done;
1748 			}
1749 			op->o_tag = modops[i].mask;
1750 		} else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod ) ) {
1751 			/* Parse attribute into modlist */
1752 			if ( si->si_syncdata == SYNCDATA_ACCESSLOG ) {
1753 				rc = syncrepl_accesslog_mods( si, bvals, &modlist );
1754 			} else {
1755 				rc = syncrepl_changelog_mods( si, bvals, &modlist );
1756 			}
1757 			if ( rc ) goto done;
1758 		} else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn ) ) {
1759 			rdn = bvals[0];
1760 		} else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn ) ) {
1761 			if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ) ) {
1762 				deleteOldRdn = 1;
1763 			}
1764 		} else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup ) ) {
1765 			sup = bvals[0];
1766 		} else if ( !ber_bvstrcasecmp( &bv,
1767 			&slap_schema.si_ad_entryCSN->ad_cname ) )
1768 		{
1769 			slap_queue_csn( op, bvals );
1770 			do_graduate = 1;
1771 		}
1772 		ch_free( bvals );
1773 	}
1774 
1775 	/* If we didn't get a mod type or a target DN, bail out */
1776 	if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn ) ) {
1777 		rc = -1;
1778 		goto done;
1779 	}
1780 
1781 	op->o_callback = &cb;
1782 	slap_op_time( &op->o_time, &op->o_tincr );
1783 
1784 	switch( op->o_tag ) {
1785 	case LDAP_REQ_ADD:
1786 	case LDAP_REQ_MODIFY:
1787 		/* If we didn't get required data, bail */
1788 		if ( !modlist ) goto done;
1789 
1790 		rc = slap_mods_check( op, modlist, &text, txtbuf, textlen, NULL );
1791 
1792 		if ( rc != LDAP_SUCCESS ) {
1793 			Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1794 				"mods check (%s)\n",
1795 				si->si_ridtxt, text, 0 );
1796 			goto done;
1797 		}
1798 
1799 		if ( op->o_tag == LDAP_REQ_ADD ) {
1800 			Entry *e = entry_alloc();
1801 			op->ora_e = e;
1802 			op->ora_e->e_name = op->o_req_dn;
1803 			op->ora_e->e_nname = op->o_req_ndn;
1804 			freeReqDn = 0;
1805 			rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1806 			if( rc != LDAP_SUCCESS ) {
1807 				Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: %s "
1808 				"mods2entry (%s)\n",
1809 					si->si_ridtxt, text, 0 );
1810 			} else {
1811 				rc = op->o_bd->be_add( op, &rs );
1812 				Debug( LDAP_DEBUG_SYNC,
1813 					"syncrepl_message_to_op: %s be_add %s (%d)\n",
1814 					si->si_ridtxt, op->o_req_dn.bv_val, rc );
1815 				do_graduate = 0;
1816 			}
1817 			if ( e == op->ora_e )
1818 				be_entry_release_w( op, op->ora_e );
1819 		} else {
1820 			op->orm_modlist = modlist;
1821 			op->o_bd = si->si_wbe;
1822 			rc = op->o_bd->be_modify( op, &rs );
1823 			modlist = op->orm_modlist;
1824 			Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1825 				"syncrepl_message_to_op: %s be_modify %s (%d)\n",
1826 				si->si_ridtxt, op->o_req_dn.bv_val, rc );
1827 			op->o_bd = si->si_be;
1828 			do_graduate = 0;
1829 		}
1830 		break;
1831 	case LDAP_REQ_MODRDN:
1832 		if ( BER_BVISNULL( &rdn ) ) goto done;
1833 
1834 		if ( rdnPretty( NULL, &rdn, &prdn, NULL ) ) {
1835 			goto done;
1836 		}
1837 		if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ) ) {
1838 			goto done;
1839 		}
1840 		if ( !BER_BVISNULL( &sup ) ) {
1841 			if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ) ) {
1842 				goto done;
1843 			}
1844 			op->orr_newSup = &psup;
1845 			op->orr_nnewSup = &nsup;
1846 		} else {
1847 			op->orr_newSup = NULL;
1848 			op->orr_nnewSup = NULL;
1849 		}
1850 		op->orr_newrdn = prdn;
1851 		op->orr_nnewrdn = nrdn;
1852 		op->orr_deleteoldrdn = deleteOldRdn;
1853 		op->orr_modlist = NULL;
1854 		if ( slap_modrdn2mods( op, &rs ) ) {
1855 			goto done;
1856 		}
1857 
1858 		/* Append modlist for operational attrs */
1859 		{
1860 			Modifications *m;
1861 
1862 			for ( m = op->orr_modlist; m->sml_next; m = m->sml_next )
1863 				;
1864 			m->sml_next = modlist;
1865 			modlist = NULL;
1866 		}
1867 		rc = op->o_bd->be_modrdn( op, &rs );
1868 		slap_mods_free( op->orr_modlist, 1 );
1869 		Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1870 			"syncrepl_message_to_op: %s be_modrdn %s (%d)\n",
1871 			si->si_ridtxt, op->o_req_dn.bv_val, rc );
1872 		do_graduate = 0;
1873 		break;
1874 	case LDAP_REQ_DELETE:
1875 		rc = op->o_bd->be_delete( op, &rs );
1876 		Debug( rc ? LDAP_DEBUG_ANY : LDAP_DEBUG_SYNC,
1877 			"syncrepl_message_to_op: %s be_delete %s (%d)\n",
1878 			si->si_ridtxt, op->o_req_dn.bv_val, rc );
1879 		do_graduate = 0;
1880 		break;
1881 	}
1882 done:
1883 	if ( do_graduate )
1884 		slap_graduate_commit_csn( op );
1885 	op->o_bd = si->si_be;
1886 	op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
1887 	BER_BVZERO( &op->o_csn );
1888 	if ( modlist ) {
1889 		slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1890 	}
1891 	if ( !BER_BVISNULL( &rdn ) ) {
1892 		if ( !BER_BVISNULL( &nsup ) ) {
1893 			ch_free( nsup.bv_val );
1894 		}
1895 		if ( !BER_BVISNULL( &psup ) ) {
1896 			ch_free( psup.bv_val );
1897 		}
1898 		if ( !BER_BVISNULL( &nrdn ) ) {
1899 			ch_free( nrdn.bv_val );
1900 		}
1901 		if ( !BER_BVISNULL( &prdn ) ) {
1902 			ch_free( prdn.bv_val );
1903 		}
1904 	}
1905 	if ( freeReqDn ) {
1906 		ch_free( op->o_req_ndn.bv_val );
1907 		ch_free( op->o_req_dn.bv_val );
1908 	}
1909 	ber_free( ber, 0 );
1910 	return rc;
1911 }
1912 
1913 static int
1914 syncrepl_message_to_entry(
1915 	syncinfo_t	*si,
1916 	Operation	*op,
1917 	LDAPMessage	*msg,
1918 	Modifications	**modlist,
1919 	Entry			**entry,
1920 	int		syncstate
1921 )
1922 {
1923 	Entry		*e = NULL;
1924 	BerElement	*ber = NULL;
1925 	Modifications	tmp;
1926 	Modifications	*mod;
1927 	Modifications	**modtail = modlist;
1928 
1929 	const char	*text;
1930 	char txtbuf[SLAP_TEXT_BUFLEN];
1931 	size_t textlen = sizeof txtbuf;
1932 
1933 	struct berval	bdn = BER_BVNULL, dn, ndn;
1934 	int		rc, is_ctx;
1935 
1936 	*modlist = NULL;
1937 
1938 	if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1939 		Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s "
1940 			"Message type should be entry (%d)",
1941 			si->si_ridtxt, ldap_msgtype( msg ), 0 );
1942 		return -1;
1943 	}
1944 
1945 	op->o_tag = LDAP_REQ_ADD;
1946 
1947 	rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1948 	if ( rc != LDAP_SUCCESS ) {
1949 		Debug( LDAP_DEBUG_ANY,
1950 			"syncrepl_message_to_entry: %s dn get failed (%d)",
1951 			si->si_ridtxt, rc, 0 );
1952 		return rc;
1953 	}
1954 
1955 	if ( BER_BVISEMPTY( &bdn ) && !BER_BVISEMPTY( &op->o_bd->be_nsuffix[0] ) ) {
1956 		Debug( LDAP_DEBUG_ANY,
1957 			"syncrepl_message_to_entry: %s got empty dn",
1958 			si->si_ridtxt, 0, 0 );
1959 		return LDAP_OTHER;
1960 	}
1961 
1962 	if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1963 		/* NOTE: this could be done even before decoding the DN,
1964 		 * although encoding errors wouldn't be detected */
1965 		rc = LDAP_SUCCESS;
1966 		goto done;
1967 	}
1968 
1969 	if ( entry == NULL ) {
1970 		return -1;
1971 	}
1972 
1973 	rc = dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1974 	if ( rc != LDAP_SUCCESS ) {
1975 		/* One of the things that could happen is that the schema
1976 		 * is not lined-up; this could result in unknown attributes.
1977 		 * A value non conformant to the syntax should be unlikely,
1978 		 * except when replicating between different versions
1979 		 * of the software, or when syntax validation bugs are fixed
1980 		 */
1981 		Debug( LDAP_DEBUG_ANY,
1982 			"syncrepl_message_to_entry: "
1983 			"%s dn \"%s\" normalization failed (%d)",
1984 			si->si_ridtxt, bdn.bv_val, rc );
1985 		return rc;
1986 	}
1987 
1988 	ber_dupbv( &op->o_req_dn, &dn );
1989 	ber_dupbv( &op->o_req_ndn, &ndn );
1990 	slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1991 	slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1992 
1993 	is_ctx = dn_match( &op->o_req_ndn, &op->o_bd->be_nsuffix[0] );
1994 
1995 	e = entry_alloc();
1996 	e->e_name = op->o_req_dn;
1997 	e->e_nname = op->o_req_ndn;
1998 
1999 	while ( ber_remaining( ber ) ) {
2000 		if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
2001 			LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
2002 		{
2003 			break;
2004 		}
2005 
2006 		/* Drop all updates to the contextCSN of the context entry
2007 		 * (ITS#4622, etc.)
2008 		 */
2009 		if ( is_ctx && !strcasecmp( tmp.sml_type.bv_val,
2010 			slap_schema.si_ad_contextCSN->ad_cname.bv_val )) {
2011 			ber_bvarray_free( tmp.sml_values );
2012 			continue;
2013 		}
2014 
2015 		mod  = (Modifications *) ch_malloc( sizeof( Modifications ) );
2016 
2017 		mod->sml_op = LDAP_MOD_REPLACE;
2018 		mod->sml_flags = 0;
2019 		mod->sml_next = NULL;
2020 		mod->sml_desc = NULL;
2021 		mod->sml_type = tmp.sml_type;
2022 		mod->sml_values = tmp.sml_values;
2023 		mod->sml_nvalues = NULL;
2024 		mod->sml_numvals = 0;	/* slap_mods_check will set this */
2025 
2026 		*modtail = mod;
2027 		modtail = &mod->sml_next;
2028 	}
2029 
2030 	if ( *modlist == NULL ) {
2031 		Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s no attributes\n",
2032 			si->si_ridtxt, 0, 0 );
2033 		rc = -1;
2034 		goto done;
2035 	}
2036 
2037 	rc = slap_mods_check( op, *modlist, &text, txtbuf, textlen, NULL );
2038 
2039 	if ( rc != LDAP_SUCCESS ) {
2040 		Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods check (%s)\n",
2041 			si->si_ridtxt, text, 0 );
2042 		goto done;
2043 	}
2044 
2045 	/* Strip out dynamically generated attrs */
2046 	for ( modtail = modlist; *modtail ; ) {
2047 		mod = *modtail;
2048 		if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
2049 			*modtail = mod->sml_next;
2050 			slap_mod_free( &mod->sml_mod, 0 );
2051 			ch_free( mod );
2052 		} else {
2053 			modtail = &mod->sml_next;
2054 		}
2055 	}
2056 
2057 	/* Strip out attrs in exattrs list */
2058 	for ( modtail = modlist; *modtail ; ) {
2059 		mod = *modtail;
2060 		if ( ldap_charray_inlist( si->si_exattrs,
2061 			mod->sml_desc->ad_type->sat_cname.bv_val ) )
2062 		{
2063 			*modtail = mod->sml_next;
2064 			slap_mod_free( &mod->sml_mod, 0 );
2065 			ch_free( mod );
2066 		} else {
2067 			modtail = &mod->sml_next;
2068 		}
2069 	}
2070 
2071 	rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
2072 	if( rc != LDAP_SUCCESS ) {
2073 		Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: %s mods2entry (%s)\n",
2074 			si->si_ridtxt, text, 0 );
2075 	}
2076 
2077 done:
2078 	ber_free( ber, 0 );
2079 	if ( rc != LDAP_SUCCESS ) {
2080 		if ( e ) {
2081 			entry_free( e );
2082 			e = NULL;
2083 		}
2084 	}
2085 	if ( entry )
2086 		*entry = e;
2087 
2088 	return rc;
2089 }
2090 
2091 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
2092 
2093 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
2094  * entry if a previous refresh was interrupted before sending us a new
2095  * context state. We try to compare the new entry to the existing entry
2096  * and ignore the new entry if they are the same.
2097  *
2098  * Also, we may get an update where the entryDN has changed, due to
2099  * a ModDn on the provider. We detect this as well, so we can issue
2100  * the corresponding operation locally.
2101  *
2102  * In the case of a modify, we get a list of all the attributes
2103  * in the original entry. Rather than deleting the entry and re-adding it,
2104  * we issue a Modify request that deletes all the attributes and adds all
2105  * the new ones. This avoids the issue of trying to delete/add a non-leaf
2106  * entry.
2107  *
2108  * We otherwise distinguish ModDN from Modify; in the case of
2109  * a ModDN we just use the CSN, modifyTimestamp and modifiersName
2110  * operational attributes from the entry, and do a regular ModDN.
2111  */
2112 typedef struct dninfo {
2113 	Entry *new_entry;
2114 	struct berval dn;
2115 	struct berval ndn;
2116 	struct berval nnewSup;
2117 	int renamed;	/* Was an existing entry renamed? */
2118 	int delOldRDN;	/* Was old RDN deleted? */
2119 	Modifications **modlist;	/* the modlist we received */
2120 	Modifications *mods;	/* the modlist we compared */
2121 	Attribute *oldNattr;	/* old naming attr */
2122 	AttributeDescription *oldDesc;	/* for renames */
2123 	AttributeDescription *newDesc;	/* for renames */
2124 } dninfo;
2125 
2126 /* return 1 if inserted, 0 otherwise */
2127 static int
2128 avl_presentlist_insert(
2129 	syncinfo_t* si,
2130 	struct berval *syncUUID )
2131 {
2132 	struct berval *syncuuid_bv = ch_malloc( sizeof( struct berval ) + syncUUID->bv_len + 1 );
2133 
2134 	syncuuid_bv->bv_len = syncUUID->bv_len;
2135 	syncuuid_bv->bv_val = (char *)&syncuuid_bv[1];
2136 	AC_MEMCPY( syncuuid_bv->bv_val, syncUUID->bv_val, syncUUID->bv_len );
2137 	syncuuid_bv->bv_val[ syncuuid_bv->bv_len ] = '\0';
2138 
2139 	if ( avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
2140 		syncuuid_cmp, avl_dup_error ) )
2141 	{
2142 		ch_free( syncuuid_bv );
2143 		return 0;
2144 	}
2145 
2146 	return 1;
2147 }
2148 
2149 static int
2150 syncrepl_entry(
2151 	syncinfo_t* si,
2152 	Operation *op,
2153 	Entry* entry,
2154 	Modifications** modlist,
2155 	int syncstate,
2156 	struct berval* syncUUID,
2157 	struct berval* syncCSN )
2158 {
2159 	Backend *be = op->o_bd;
2160 	slap_callback	cb = { NULL, NULL, NULL, NULL };
2161 	int syncuuid_inserted = 0;
2162 	struct berval	syncUUID_strrep = BER_BVNULL;
2163 
2164 	SlapReply	rs_search = {REP_RESULT};
2165 	SlapReply	rs_delete = {REP_RESULT};
2166 	SlapReply	rs_add = {REP_RESULT};
2167 	SlapReply	rs_modify = {REP_RESULT};
2168 	Filter f = {0};
2169 	AttributeAssertion ava = ATTRIBUTEASSERTION_INIT;
2170 	int rc = LDAP_SUCCESS;
2171 
2172 	struct berval pdn = BER_BVNULL;
2173 	dninfo dni = {0};
2174 	int	retry = 1;
2175 	int	freecsn = 1;
2176 
2177 	Debug( LDAP_DEBUG_SYNC,
2178 		"syncrepl_entry: %s LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_%s)\n",
2179 		si->si_ridtxt, syncrepl_state2str( syncstate ), 0 );
2180 
2181 	if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD ) ) {
2182 		if ( !si->si_refreshPresent && !si->si_refreshDone ) {
2183 			syncuuid_inserted = avl_presentlist_insert( si, syncUUID );
2184 		}
2185 	}
2186 
2187 	if ( syncstate == LDAP_SYNC_PRESENT ) {
2188 		return 0;
2189 	} else if ( syncstate != LDAP_SYNC_DELETE ) {
2190 		if ( entry == NULL ) {
2191 			return 0;
2192 		}
2193 	}
2194 
2195 	(void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
2196 	if ( syncstate != LDAP_SYNC_DELETE ) {
2197 		Attribute	*a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
2198 
2199 		if ( a == NULL ) {
2200 			/* add if missing */
2201 			attr_merge_one( entry, slap_schema.si_ad_entryUUID,
2202 				&syncUUID_strrep, syncUUID );
2203 
2204 		} else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
2205 			/* replace only if necessary */
2206 			if ( a->a_nvals != a->a_vals ) {
2207 				ber_memfree( a->a_nvals[0].bv_val );
2208 				ber_dupbv( &a->a_nvals[0], syncUUID );
2209 			}
2210 			ber_memfree( a->a_vals[0].bv_val );
2211 			ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
2212 		}
2213 	}
2214 
2215 	f.f_choice = LDAP_FILTER_EQUALITY;
2216 	f.f_ava = &ava;
2217 	ava.aa_desc = slap_schema.si_ad_entryUUID;
2218 	ava.aa_value = *syncUUID;
2219 
2220 	if ( syncuuid_inserted ) {
2221 		Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: %s inserted UUID %s\n",
2222 			si->si_ridtxt, syncUUID_strrep.bv_val, 0 );
2223 	}
2224 	op->ors_filter = &f;
2225 
2226 	op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
2227 	op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
2228 		op->ors_filterstr.bv_len + 1, op->o_tmpmemctx );
2229 	AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
2230 	AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
2231 		syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
2232 	op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
2233 	op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
2234 
2235 	op->o_tag = LDAP_REQ_SEARCH;
2236 	op->ors_scope = LDAP_SCOPE_SUBTREE;
2237 	op->ors_deref = LDAP_DEREF_NEVER;
2238 
2239 	/* get the entry for this UUID */
2240 	op->o_req_dn = si->si_base;
2241 	op->o_req_ndn = si->si_base;
2242 
2243 	op->o_time = slap_get_time();
2244 	op->ors_tlimit = SLAP_NO_LIMIT;
2245 	op->ors_slimit = 1;
2246 	op->ors_limit = NULL;
2247 
2248 	op->ors_attrs = slap_anlist_all_attributes;
2249 	op->ors_attrsonly = 0;
2250 
2251 	/* set callback function */
2252 	op->o_callback = &cb;
2253 	cb.sc_response = dn_callback;
2254 	cb.sc_private = &dni;
2255 	dni.new_entry = entry;
2256 	dni.modlist = modlist;
2257 
2258 	rc = be->be_search( op, &rs_search );
2259 	Debug( LDAP_DEBUG_SYNC,
2260 			"syncrepl_entry: %s be_search (%d)\n",
2261 			si->si_ridtxt, rc, 0 );
2262 
2263 	if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
2264 		slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2265 	}
2266 
2267 	cb.sc_response = null_callback;
2268 	cb.sc_private = si;
2269 
2270 	if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
2271 		Debug( LDAP_DEBUG_SYNC,
2272 				"syncrepl_entry: %s %s\n",
2273 				si->si_ridtxt, entry->e_name.bv_val, 0 );
2274 	} else {
2275 		Debug( LDAP_DEBUG_SYNC,
2276 				"syncrepl_entry: %s %s\n",
2277 				si->si_ridtxt, dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0 );
2278 	}
2279 
2280 	assert( BER_BVISNULL( &op->o_csn ) );
2281 	if ( syncCSN ) {
2282 		slap_queue_csn( op, syncCSN );
2283 	}
2284 
2285 	slap_op_time( &op->o_time, &op->o_tincr );
2286 	switch ( syncstate ) {
2287 	case LDAP_SYNC_ADD:
2288 	case LDAP_SYNC_MODIFY:
2289 		if ( BER_BVISNULL( &op->o_csn ))
2290 		{
2291 
2292 			Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
2293 			if ( a ) {
2294 				/* FIXME: op->o_csn is assumed to be
2295 				 * on the thread's slab; this needs
2296 				 * to be cleared ASAP.
2297 				 * What happens if already present?
2298 				 */
2299 				assert( BER_BVISNULL( &op->o_csn ) );
2300 				op->o_csn = a->a_vals[0];
2301 				freecsn = 0;
2302 			}
2303 		}
2304 retry_add:;
2305 		if ( BER_BVISNULL( &dni.dn ) ) {
2306 
2307 			op->o_req_dn = entry->e_name;
2308 			op->o_req_ndn = entry->e_nname;
2309 			op->o_tag = LDAP_REQ_ADD;
2310 			op->ora_e = entry;
2311 			op->o_bd = si->si_wbe;
2312 
2313 			rc = op->o_bd->be_add( op, &rs_add );
2314 			Debug( LDAP_DEBUG_SYNC,
2315 					"syncrepl_entry: %s be_add %s (%d)\n",
2316 					si->si_ridtxt, op->o_req_dn.bv_val, rc );
2317 			switch ( rs_add.sr_err ) {
2318 			case LDAP_SUCCESS:
2319 				if ( op->ora_e == entry ) {
2320 					be_entry_release_w( op, entry );
2321 				}
2322 				entry = NULL;
2323 				break;
2324 
2325 			case LDAP_REFERRAL:
2326 			/* we assume that LDAP_NO_SUCH_OBJECT is returned
2327 			 * only if the suffix entry is not present */
2328 			case LDAP_NO_SUCH_OBJECT:
2329 				rc = syncrepl_add_glue( op, entry );
2330 				entry = NULL;
2331 				break;
2332 
2333 			/* if an entry was added via syncrepl_add_glue(),
2334 			 * it likely has no entryUUID, so the previous
2335 			 * be_search() doesn't find it.  In this case,
2336 			 * give syncrepl a chance to modify it. Also
2337 			 * allow for entries that were recreated with the
2338 			 * same DN but a different entryUUID.
2339 			 */
2340 			case LDAP_ALREADY_EXISTS:
2341 				if ( retry ) {
2342 					Operation	op2 = *op;
2343 					SlapReply	rs2 = { 0 };
2344 					slap_callback	cb2 = { 0 };
2345 
2346 					op2.o_bd = be;
2347 					op2.o_tag = LDAP_REQ_SEARCH;
2348 					op2.o_req_dn = entry->e_name;
2349 					op2.o_req_ndn = entry->e_nname;
2350 					op2.ors_scope = LDAP_SCOPE_BASE;
2351 					op2.ors_deref = LDAP_DEREF_NEVER;
2352 					op2.ors_attrs = slap_anlist_all_attributes;
2353 					op2.ors_attrsonly = 0;
2354 					op2.ors_limit = NULL;
2355 					op2.ors_slimit = 1;
2356 					op2.ors_tlimit = SLAP_NO_LIMIT;
2357 
2358 					f.f_choice = LDAP_FILTER_PRESENT;
2359 					f.f_desc = slap_schema.si_ad_objectClass;
2360 					op2.ors_filter = &f;
2361 					op2.ors_filterstr = generic_filterstr;
2362 
2363 					op2.o_callback = &cb2;
2364 					cb2.sc_response = dn_callback;
2365 					cb2.sc_private = &dni;
2366 
2367 					rc = be->be_search( &op2, &rs2 );
2368 					if ( rc ) goto done;
2369 
2370 					retry = 0;
2371 					slap_op_time( &op->o_time, &op->o_tincr );
2372 					goto retry_add;
2373 				}
2374 				/* FALLTHRU */
2375 
2376 			default:
2377 				Debug( LDAP_DEBUG_ANY,
2378 					"syncrepl_entry: %s be_add %s failed (%d)\n",
2379 					si->si_ridtxt, op->o_req_dn.bv_val, rs_add.sr_err );
2380 				break;
2381 			}
2382 			syncCSN = NULL;
2383 			op->o_bd = be;
2384 			goto done;
2385 		}
2386 		/* FALLTHRU */
2387 		op->o_req_dn = dni.dn;
2388 		op->o_req_ndn = dni.ndn;
2389 		if ( dni.renamed ) {
2390 			struct berval noldp, newp;
2391 			Modifications *mod, **modtail, **ml, *m2;
2392 			int i, got_replace = 0, just_rename = 0;
2393 
2394 			op->o_tag = LDAP_REQ_MODRDN;
2395 			dnRdn( &entry->e_name, &op->orr_newrdn );
2396 			dnRdn( &entry->e_nname, &op->orr_nnewrdn );
2397 
2398 			if ( !BER_BVISNULL( &dni.nnewSup )) {
2399 				dnParent( &entry->e_name, &newp );
2400 				op->orr_newSup = &newp;
2401 				op->orr_nnewSup = &dni.nnewSup;
2402 			} else {
2403 				op->orr_newSup = NULL;
2404 				op->orr_nnewSup = NULL;
2405 			}
2406 			op->orr_deleteoldrdn = dni.delOldRDN;
2407 			op->orr_modlist = NULL;
2408 			if ( ( rc = slap_modrdn2mods( op, &rs_modify ) ) ) {
2409 				goto done;
2410 			}
2411 
2412 			/* Drop the RDN-related mods from this op, because their
2413 			 * equivalents were just setup by slap_modrdn2mods.
2414 			 *
2415 			 * If delOldRDN is TRUE then we should see a delete modop
2416 			 * for oldDesc. We might see a replace instead.
2417 			 *  delete with no values: therefore newDesc != oldDesc.
2418 			 *   if oldNattr had only one value, then Drop this op.
2419 			 *  delete with 1 value: can only be the oldRDN value. Drop op.
2420 			 *  delete with N values: Drop oldRDN value, keep remainder.
2421 			 *  replace with 1 value: if oldNattr had only one value and
2422 			 *     newDesc == oldDesc, Drop this op.
2423 			 * Any other cases must be left intact.
2424 			 *
2425 			 * We should also see an add modop for newDesc. (But not if
2426 			 * we got a replace modop due to delOldRDN.) If it has
2427 			 * multiple values, we'll have to drop the new RDN value.
2428 			 */
2429 			modtail = &op->orr_modlist;
2430 			if ( dni.delOldRDN ) {
2431 				for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2432 					if ( (*ml)->sml_desc == dni.oldDesc ) {
2433 						mod = *ml;
2434 						if ( mod->sml_op == LDAP_MOD_REPLACE &&
2435 							dni.oldDesc != dni.newDesc ) {
2436 							/* This Replace is due to other Mods.
2437 							 * Just let it ride.
2438 							 */
2439 							continue;
2440 						}
2441 						if ( mod->sml_numvals <= 1 &&
2442 							dni.oldNattr->a_numvals == 1 &&
2443 							( mod->sml_op == LDAP_MOD_DELETE ||
2444 							  mod->sml_op == LDAP_MOD_REPLACE )) {
2445 							if ( mod->sml_op == LDAP_MOD_REPLACE )
2446 								got_replace = 1;
2447 							/* Drop this op */
2448 							*ml = mod->sml_next;
2449 							mod->sml_next = NULL;
2450 							slap_mods_free( mod, 1 );
2451 							break;
2452 						}
2453 						if ( mod->sml_op != LDAP_MOD_DELETE || mod->sml_numvals == 0 )
2454 							continue;
2455 						for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2456 							if ( m2->sml_desc == dni.oldDesc &&
2457 								m2->sml_op == LDAP_MOD_DELETE ) break;
2458 						}
2459 						for ( i=0; i<mod->sml_numvals; i++ ) {
2460 							if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2461 								mod->sml_numvals--;
2462 								ch_free( mod->sml_values[i].bv_val );
2463 								mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2464 								BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2465 								if ( mod->sml_nvalues ) {
2466 									ch_free( mod->sml_nvalues[i].bv_val );
2467 									mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
2468 									BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
2469 								}
2470 								break;
2471 							}
2472 						}
2473 						if ( !mod->sml_numvals ) {
2474 							/* Drop this op */
2475 							*ml = mod->sml_next;
2476 							mod->sml_next = NULL;
2477 							slap_mods_free( mod, 1 );
2478 						}
2479 						break;
2480 					}
2481 				}
2482 			}
2483 			if ( !got_replace ) {
2484 				for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next ) {
2485 					if ( (*ml)->sml_desc == dni.newDesc ) {
2486 						mod = *ml;
2487 						if ( mod->sml_op != LDAP_MOD_ADD )
2488 							continue;
2489 						if ( mod->sml_numvals == 1 ) {
2490 							/* Drop this op */
2491 							*ml = mod->sml_next;
2492 							mod->sml_next = NULL;
2493 							slap_mods_free( mod, 1 );
2494 							break;
2495 						}
2496 						for ( m2 = op->orr_modlist; m2; m2=m2->sml_next ) {
2497 							if ( m2->sml_desc == dni.oldDesc &&
2498 								m2->sml_op == SLAP_MOD_SOFTADD ) break;
2499 						}
2500 						for ( i=0; i<mod->sml_numvals; i++ ) {
2501 							if ( bvmatch( &mod->sml_values[i], &m2->sml_values[0] )) {
2502 								mod->sml_numvals--;
2503 								ch_free( mod->sml_values[i].bv_val );
2504 								mod->sml_values[i] = mod->sml_values[mod->sml_numvals];
2505 								BER_BVZERO( &mod->sml_values[mod->sml_numvals] );
2506 								if ( mod->sml_nvalues ) {
2507 									ch_free( mod->sml_nvalues[i].bv_val );
2508 									mod->sml_nvalues[i] = mod->sml_nvalues[mod->sml_numvals];
2509 									BER_BVZERO( &mod->sml_nvalues[mod->sml_numvals] );
2510 								}
2511 								break;
2512 							}
2513 						}
2514 						break;
2515 					}
2516 				}
2517 			}
2518 
2519 			/* RDNs must be NUL-terminated for back-ldap */
2520 			noldp = op->orr_newrdn;
2521 			ber_dupbv_x( &op->orr_newrdn, &noldp, op->o_tmpmemctx );
2522 			noldp = op->orr_nnewrdn;
2523 			ber_dupbv_x( &op->orr_nnewrdn, &noldp, op->o_tmpmemctx );
2524 
2525 			/* Setup opattrs too */
2526 			{
2527 				static AttributeDescription *nullattr = NULL;
2528 				static AttributeDescription **const opattrs[] = {
2529 					&slap_schema.si_ad_entryCSN,
2530 					&slap_schema.si_ad_modifiersName,
2531 					&slap_schema.si_ad_modifyTimestamp,
2532 					&nullattr
2533 				};
2534 				AttributeDescription *opattr;
2535 				int i;
2536 
2537 				modtail = &m2;
2538 				/* pull mod off incoming modlist */
2539 				for ( i = 0; (opattr = *opattrs[i]) != NULL; i++ ) {
2540 					for ( ml = &dni.mods; *ml; ml = &(*ml)->sml_next )
2541 					{
2542 						if ( (*ml)->sml_desc == opattr ) {
2543 							mod = *ml;
2544 							*ml = mod->sml_next;
2545 							mod->sml_next = NULL;
2546 							*modtail = mod;
2547 							modtail = &mod->sml_next;
2548 							break;
2549 						}
2550 					}
2551 				}
2552 				/* If there are still Modifications left, put the opattrs
2553 				 * back, and let be_modify run. Otherwise, append the opattrs
2554 				 * to the orr_modlist.
2555 				 */
2556 				if ( dni.mods ) {
2557 					mod = dni.mods;
2558 					/* don't set a CSN for the rename op */
2559 					if ( syncCSN )
2560 						slap_graduate_commit_csn( op );
2561 				} else {
2562 					mod = op->orr_modlist;
2563 					just_rename = 1;
2564 				}
2565 				for ( ; mod->sml_next; mod=mod->sml_next );
2566 				mod->sml_next = m2;
2567 			}
2568 			op->o_bd = si->si_wbe;
2569 retry_modrdn:;
2570 			rc = op->o_bd->be_modrdn( op, &rs_modify );
2571 
2572 			/* NOTE: noSuchObject should result because the new superior
2573 			 * has not been added yet (ITS#6472) */
2574 			if ( rc == LDAP_NO_SUCH_OBJECT && !BER_BVISNULL( op->orr_nnewSup )) {
2575 				Operation op2 = *op;
2576 				rc = syncrepl_add_glue_ancestors( &op2, entry );
2577 				if ( rc == LDAP_SUCCESS ) {
2578 					goto retry_modrdn;
2579 				}
2580 			}
2581 
2582 			op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
2583 			op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
2584 
2585 			slap_mods_free( op->orr_modlist, 1 );
2586 			Debug( LDAP_DEBUG_SYNC,
2587 					"syncrepl_entry: %s be_modrdn %s (%d)\n",
2588 					si->si_ridtxt, op->o_req_dn.bv_val, rc );
2589 			op->o_bd = be;
2590 			/* Renamed entries may still have other mods so just fallthru */
2591 			op->o_req_dn = entry->e_name;
2592 			op->o_req_ndn = entry->e_nname;
2593 			/* Use CSN on the modify */
2594 			if ( just_rename )
2595 				syncCSN = NULL;
2596 			else if ( syncCSN )
2597 				slap_queue_csn( op, syncCSN );
2598 		}
2599 		if ( dni.mods ) {
2600 			op->o_tag = LDAP_REQ_MODIFY;
2601 			op->orm_modlist = dni.mods;
2602 			op->orm_no_opattrs = 1;
2603 			op->o_bd = si->si_wbe;
2604 
2605 			rc = op->o_bd->be_modify( op, &rs_modify );
2606 			slap_mods_free( op->orm_modlist, 1 );
2607 			op->orm_no_opattrs = 0;
2608 			Debug( LDAP_DEBUG_SYNC,
2609 					"syncrepl_entry: %s be_modify %s (%d)\n",
2610 					si->si_ridtxt, op->o_req_dn.bv_val, rc );
2611 			if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2612 				Debug( LDAP_DEBUG_ANY,
2613 					"syncrepl_entry: %s be_modify failed (%d)\n",
2614 					si->si_ridtxt, rs_modify.sr_err, 0 );
2615 			}
2616 			syncCSN = NULL;
2617 			op->o_bd = be;
2618 		} else if ( !dni.renamed ) {
2619 			Debug( LDAP_DEBUG_SYNC,
2620 					"syncrepl_entry: %s entry unchanged, ignored (%s)\n",
2621 					si->si_ridtxt, op->o_req_dn.bv_val, 0 );
2622 			if ( syncCSN ) {
2623 				slap_graduate_commit_csn( op );
2624 				syncCSN = NULL;
2625 			}
2626 		}
2627 		goto done;
2628 	case LDAP_SYNC_DELETE :
2629 		if ( !BER_BVISNULL( &dni.dn ) ) {
2630 			op->o_req_dn = dni.dn;
2631 			op->o_req_ndn = dni.ndn;
2632 			op->o_tag = LDAP_REQ_DELETE;
2633 			op->o_bd = si->si_wbe;
2634 			rc = op->o_bd->be_delete( op, &rs_delete );
2635 			Debug( LDAP_DEBUG_SYNC,
2636 					"syncrepl_entry: %s be_delete %s (%d)\n",
2637 					si->si_ridtxt, op->o_req_dn.bv_val, rc );
2638 
2639 			while ( rs_delete.sr_err == LDAP_SUCCESS
2640 				&& op->o_delete_glue_parent ) {
2641 				op->o_delete_glue_parent = 0;
2642 				if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2643 					slap_callback cb = { NULL };
2644 					cb.sc_response = slap_null_cb;
2645 					dnParent( &op->o_req_ndn, &pdn );
2646 					op->o_req_dn = pdn;
2647 					op->o_req_ndn = pdn;
2648 					op->o_callback = &cb;
2649 					op->o_bd->be_delete( op, &rs_delete );
2650 				} else {
2651 					break;
2652 				}
2653 			}
2654 			syncCSN = NULL;
2655 			op->o_bd = be;
2656 		}
2657 		goto done;
2658 
2659 	default :
2660 		Debug( LDAP_DEBUG_ANY,
2661 			"syncrepl_entry: %s unknown syncstate\n", si->si_ridtxt, 0, 0 );
2662 		goto done;
2663 	}
2664 
2665 done:
2666 	if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
2667 		slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
2668 		BER_BVZERO( &syncUUID_strrep );
2669 	}
2670 	if ( !BER_BVISNULL( &dni.ndn ) ) {
2671 		op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2672 	}
2673 	if ( !BER_BVISNULL( &dni.dn ) ) {
2674 		op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2675 	}
2676 	if ( entry ) {
2677 		entry_free( entry );
2678 	}
2679 	if ( syncCSN ) {
2680 		slap_graduate_commit_csn( op );
2681 	}
2682 	if ( !BER_BVISNULL( &op->o_csn ) && freecsn ) {
2683 		op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2684 	}
2685 	BER_BVZERO( &op->o_csn );
2686 	return rc;
2687 }
2688 
2689 static struct berval gcbva[] = {
2690 	BER_BVC("top"),
2691 	BER_BVC("glue"),
2692 	BER_BVNULL
2693 };
2694 
2695 #define NP_DELETE_ONE	2
2696 
2697 static void
2698 syncrepl_del_nonpresent(
2699 	Operation *op,
2700 	syncinfo_t *si,
2701 	BerVarray uuids,
2702 	struct sync_cookie *sc,
2703 	int m )
2704 {
2705 	Backend* be = op->o_bd;
2706 	slap_callback	cb = { NULL };
2707 	SlapReply	rs_search = {REP_RESULT};
2708 	SlapReply	rs_delete = {REP_RESULT};
2709 	SlapReply	rs_modify = {REP_RESULT};
2710 	struct nonpresent_entry *np_list, *np_prev;
2711 	int rc;
2712 	AttributeName	an[2];
2713 
2714 	struct berval pdn = BER_BVNULL;
2715 	struct berval csn;
2716 
2717 	op->o_req_dn = si->si_base;
2718 	op->o_req_ndn = si->si_base;
2719 
2720 	cb.sc_response = nonpresent_callback;
2721 	cb.sc_private = si;
2722 
2723 	op->o_callback = &cb;
2724 	op->o_tag = LDAP_REQ_SEARCH;
2725 	op->ors_scope = si->si_scope;
2726 	op->ors_deref = LDAP_DEREF_NEVER;
2727 	op->o_time = slap_get_time();
2728 	op->ors_tlimit = SLAP_NO_LIMIT;
2729 
2730 
2731 	if ( uuids ) {
2732 		Filter uf;
2733 		AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
2734 		int i;
2735 
2736 		op->ors_attrsonly = 1;
2737 		op->ors_attrs = slap_anlist_no_attrs;
2738 		op->ors_limit = NULL;
2739 		op->ors_filter = &uf;
2740 
2741 		uf.f_ava = &eq;
2742 		uf.f_av_desc = slap_schema.si_ad_entryUUID;
2743 		uf.f_next = NULL;
2744 		uf.f_choice = LDAP_FILTER_EQUALITY;
2745 		si->si_refreshDelete |= NP_DELETE_ONE;
2746 
2747 		for (i=0; uuids[i].bv_val; i++) {
2748 			op->ors_slimit = 1;
2749 			uf.f_av_value = uuids[i];
2750 			filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2751 			rc = be->be_search( op, &rs_search );
2752 			op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2753 		}
2754 		si->si_refreshDelete ^= NP_DELETE_ONE;
2755 	} else {
2756 		Filter *cf, *of;
2757 		Filter mmf[2];
2758 		AttributeAssertion mmaa;
2759 
2760 		memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2761 		an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2762 		an[0].an_desc = slap_schema.si_ad_entryUUID;
2763 		op->ors_attrs = an;
2764 		op->ors_slimit = SLAP_NO_LIMIT;
2765 		op->ors_tlimit = SLAP_NO_LIMIT;
2766 		op->ors_limit = NULL;
2767 		op->ors_attrsonly = 0;
2768 		op->ors_filter = filter_dup( si->si_filter, op->o_tmpmemctx );
2769 		/* In multimaster, updates can continue to arrive while
2770 		 * we're searching. Limit the search result to entries
2771 		 * older than our newest cookie CSN.
2772 		 */
2773 		if ( SLAP_MULTIMASTER( op->o_bd )) {
2774 			Filter *f;
2775 			int i;
2776 
2777 			f = mmf;
2778 			f->f_choice = LDAP_FILTER_AND;
2779 			f->f_next = op->ors_filter;
2780 			f->f_and = f+1;
2781 			of = f->f_and;
2782 			f = of;
2783 			f->f_choice = LDAP_FILTER_LE;
2784 			f->f_ava = &mmaa;
2785 			f->f_av_desc = slap_schema.si_ad_entryCSN;
2786 			f->f_next = NULL;
2787 			BER_BVZERO( &f->f_av_value );
2788 			for ( i=0; i<sc->numcsns; i++ ) {
2789 				if ( ber_bvcmp( &sc->ctxcsn[i], &f->f_av_value ) > 0 )
2790 					f->f_av_value = sc->ctxcsn[i];
2791 			}
2792 			of = op->ors_filter;
2793 			op->ors_filter = mmf;
2794 			filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2795 		} else {
2796 			cf = NULL;
2797 			op->ors_filterstr = si->si_filterstr;
2798 		}
2799 		op->o_nocaching = 1;
2800 
2801 
2802 		rc = be->be_search( op, &rs_search );
2803 		if ( SLAP_MULTIMASTER( op->o_bd )) {
2804 			op->ors_filter = of;
2805 		}
2806 		if ( op->ors_filter ) filter_free_x( op, op->ors_filter, 1 );
2807 		if ( op->ors_filterstr.bv_val != si->si_filterstr.bv_val ) {
2808 			op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2809 		}
2810 
2811 	}
2812 
2813 	op->o_nocaching = 0;
2814 
2815 	if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2816 
2817 		if ( sc->ctxcsn && !BER_BVISNULL( &sc->ctxcsn[m] ) ) {
2818 			csn = sc->ctxcsn[m];
2819 		} else {
2820 			csn = si->si_syncCookie.ctxcsn[0];
2821 		}
2822 
2823 		op->o_bd = si->si_wbe;
2824 		slap_queue_csn( op, &csn );
2825 
2826 		np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2827 		while ( np_list != NULL ) {
2828 			LDAP_LIST_REMOVE( np_list, npe_link );
2829 			np_prev = np_list;
2830 			np_list = LDAP_LIST_NEXT( np_list, npe_link );
2831 			op->o_tag = LDAP_REQ_DELETE;
2832 			op->o_callback = &cb;
2833 			cb.sc_response = null_callback;
2834 			cb.sc_private = si;
2835 			op->o_req_dn = *np_prev->npe_name;
2836 			op->o_req_ndn = *np_prev->npe_nname;
2837 			rc = op->o_bd->be_delete( op, &rs_delete );
2838 			Debug( LDAP_DEBUG_SYNC,
2839 				"syncrepl_del_nonpresent: %s be_delete %s (%d)\n",
2840 				si->si_ridtxt, op->o_req_dn.bv_val, rc );
2841 
2842 			if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2843 				Modifications mod1, mod2;
2844 				mod1.sml_op = LDAP_MOD_REPLACE;
2845 				mod1.sml_flags = 0;
2846 				mod1.sml_desc = slap_schema.si_ad_objectClass;
2847 				mod1.sml_type = mod1.sml_desc->ad_cname;
2848 				mod1.sml_numvals = 2;
2849 				mod1.sml_values = &gcbva[0];
2850 				mod1.sml_nvalues = NULL;
2851 				mod1.sml_next = &mod2;
2852 
2853 				mod2.sml_op = LDAP_MOD_REPLACE;
2854 				mod2.sml_flags = 0;
2855 				mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2856 				mod2.sml_type = mod2.sml_desc->ad_cname;
2857 				mod2.sml_numvals = 1;
2858 				mod2.sml_values = &gcbva[1];
2859 				mod2.sml_nvalues = NULL;
2860 				mod2.sml_next = NULL;
2861 
2862 				op->o_tag = LDAP_REQ_MODIFY;
2863 				op->orm_modlist = &mod1;
2864 
2865 				rc = op->o_bd->be_modify( op, &rs_modify );
2866 				if ( mod2.sml_next ) slap_mods_free( mod2.sml_next, 1 );
2867 			}
2868 
2869 			while ( rs_delete.sr_err == LDAP_SUCCESS &&
2870 					op->o_delete_glue_parent ) {
2871 				op->o_delete_glue_parent = 0;
2872 				if ( !be_issuffix( be, &op->o_req_ndn ) ) {
2873 					slap_callback cb = { NULL };
2874 					cb.sc_response = slap_null_cb;
2875 					dnParent( &op->o_req_ndn, &pdn );
2876 					op->o_req_dn = pdn;
2877 					op->o_req_ndn = pdn;
2878 					op->o_callback = &cb;
2879 					/* give it a root privil ? */
2880 					op->o_bd->be_delete( op, &rs_delete );
2881 				} else {
2882 					break;
2883 				}
2884 			}
2885 
2886 			op->o_delete_glue_parent = 0;
2887 
2888 			ber_bvfree( np_prev->npe_name );
2889 			ber_bvfree( np_prev->npe_nname );
2890 			ch_free( np_prev );
2891 
2892 			if ( slapd_shutdown ) {
2893 				break;
2894 			}
2895 		}
2896 
2897 		slap_graduate_commit_csn( op );
2898 		op->o_bd = be;
2899 
2900 		op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2901 		BER_BVZERO( &op->o_csn );
2902 	}
2903 
2904 	return;
2905 }
2906 
2907 static int
2908 syncrepl_add_glue_ancestors(
2909 	Operation* op,
2910 	Entry *e )
2911 {
2912 	Backend *be = op->o_bd;
2913 	slap_callback cb = { NULL };
2914 	Attribute	*a;
2915 	int	rc;
2916 	int suffrdns;
2917 	int i;
2918 	struct berval dn = BER_BVNULL;
2919 	struct berval ndn = BER_BVNULL;
2920 	Entry	*glue;
2921 	SlapReply	rs_add = {REP_RESULT};
2922 	struct berval	ptr, nptr;
2923 	char		*comma;
2924 
2925 	op->o_tag = LDAP_REQ_ADD;
2926 	op->o_callback = &cb;
2927 	cb.sc_response = null_callback;
2928 	cb.sc_private = NULL;
2929 
2930 	dn = e->e_name;
2931 	ndn = e->e_nname;
2932 
2933 	/* count RDNs in suffix */
2934 	if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2935 		for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2936 			comma++;
2937 			ptr.bv_len -= comma - ptr.bv_val;
2938 			ptr.bv_val = comma;
2939 			i++;
2940 		}
2941 		suffrdns = i;
2942 	} else {
2943 		/* suffix is "" */
2944 		suffrdns = 0;
2945 	}
2946 
2947 	/* Start with BE suffix */
2948 	ptr = dn;
2949 	for ( i = 0; i < suffrdns; i++ ) {
2950 		comma = ber_bvrchr( &ptr, ',' );
2951 		if ( comma != NULL ) {
2952 			ptr.bv_len = comma - ptr.bv_val;
2953 		} else {
2954 			ptr.bv_len = 0;
2955 			break;
2956 		}
2957 	}
2958 
2959 	if ( !BER_BVISEMPTY( &ptr ) ) {
2960 		dn.bv_len -= ptr.bv_len + 1;
2961 		dn.bv_val += ptr.bv_len + 1;
2962 	}
2963 
2964 	/* the normalizedDNs are always the same length, no counting
2965 	 * required.
2966 	 */
2967 	nptr = ndn;
2968 	if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2969 		ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2970 		ndn.bv_len = be->be_nsuffix[0].bv_len;
2971 
2972 		nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2973 
2974 	} else {
2975 		nptr.bv_len = 0;
2976 	}
2977 
2978 	while ( ndn.bv_val > e->e_nname.bv_val ) {
2979 		glue = entry_alloc();
2980 		ber_dupbv( &glue->e_name, &dn );
2981 		ber_dupbv( &glue->e_nname, &ndn );
2982 
2983 		a = attr_alloc( slap_schema.si_ad_objectClass );
2984 
2985 		a->a_numvals = 2;
2986 		a->a_vals = ch_calloc( 3, sizeof( struct berval ) );
2987 		ber_dupbv( &a->a_vals[0], &gcbva[0] );
2988 		ber_dupbv( &a->a_vals[1], &gcbva[1] );
2989 		ber_dupbv( &a->a_vals[2], &gcbva[2] );
2990 
2991 		a->a_nvals = a->a_vals;
2992 
2993 		a->a_next = glue->e_attrs;
2994 		glue->e_attrs = a;
2995 
2996 		a = attr_alloc( slap_schema.si_ad_structuralObjectClass );
2997 
2998 		a->a_numvals = 1;
2999 		a->a_vals = ch_calloc( 2, sizeof( struct berval ) );
3000 		ber_dupbv( &a->a_vals[0], &gcbva[1] );
3001 		ber_dupbv( &a->a_vals[1], &gcbva[2] );
3002 
3003 		a->a_nvals = a->a_vals;
3004 
3005 		a->a_next = glue->e_attrs;
3006 		glue->e_attrs = a;
3007 
3008 		op->o_req_dn = glue->e_name;
3009 		op->o_req_ndn = glue->e_nname;
3010 		op->ora_e = glue;
3011 		rc = be->be_add ( op, &rs_add );
3012 		if ( rs_add.sr_err == LDAP_SUCCESS ) {
3013 			if ( op->ora_e == glue )
3014 				be_entry_release_w( op, glue );
3015 		} else {
3016 		/* incl. ALREADY EXIST */
3017 			entry_free( glue );
3018 			if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
3019 				entry_free( e );
3020 				return rc;
3021 			}
3022 		}
3023 
3024 		/* Move to next child */
3025 		comma = ber_bvrchr( &ptr, ',' );
3026 		if ( comma == NULL ) {
3027 			break;
3028 		}
3029 		ptr.bv_len = comma - ptr.bv_val;
3030 
3031 		dn.bv_val = ++comma;
3032 		dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
3033 
3034 		comma = ber_bvrchr( &nptr, ',' );
3035 		assert( comma != NULL );
3036 		nptr.bv_len = comma - nptr.bv_val;
3037 
3038 		ndn.bv_val = ++comma;
3039 		ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
3040 	}
3041 
3042 	return rc;
3043 }
3044 
3045 int
3046 syncrepl_add_glue(
3047 	Operation* op,
3048 	Entry *e )
3049 {
3050 	slap_callback cb = { NULL };
3051 	int	rc;
3052 	Backend *be = op->o_bd;
3053 	SlapReply	rs_add = {REP_RESULT};
3054 
3055 	rc = syncrepl_add_glue_ancestors( op, e );
3056 	switch ( rc ) {
3057 	case LDAP_SUCCESS:
3058 	case LDAP_ALREADY_EXISTS:
3059 		break;
3060 
3061 	default:
3062 		return rc;
3063 	}
3064 
3065 	op->o_tag = LDAP_REQ_ADD;
3066 	op->o_callback = &cb;
3067 	cb.sc_response = null_callback;
3068 	cb.sc_private = NULL;
3069 
3070 	op->o_req_dn = e->e_name;
3071 	op->o_req_ndn = e->e_nname;
3072 	op->ora_e = e;
3073 	rc = be->be_add ( op, &rs_add );
3074 	if ( rs_add.sr_err == LDAP_SUCCESS ) {
3075 		if ( op->ora_e == e )
3076 			be_entry_release_w( op, e );
3077 	} else {
3078 		entry_free( e );
3079 	}
3080 
3081 	return rc;
3082 }
3083 
3084 static int
3085 syncrepl_updateCookie(
3086 	syncinfo_t *si,
3087 	Operation *op,
3088 	struct sync_cookie *syncCookie )
3089 {
3090 	Backend *be = op->o_bd;
3091 	Modifications mod;
3092 	struct berval first = BER_BVNULL;
3093 #ifdef CHECK_CSN
3094 	Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
3095 #endif
3096 
3097 	int rc, i, j, changed = 0;
3098 	ber_len_t len;
3099 
3100 	slap_callback cb = { NULL };
3101 	SlapReply	rs_modify = {REP_RESULT};
3102 
3103 	mod.sml_op = LDAP_MOD_REPLACE;
3104 	mod.sml_desc = slap_schema.si_ad_contextCSN;
3105 	mod.sml_type = mod.sml_desc->ad_cname;
3106 	mod.sml_flags = SLAP_MOD_INTERNAL;
3107 	mod.sml_nvalues = NULL;
3108 	mod.sml_next = NULL;
3109 
3110 	ldap_pvt_thread_mutex_lock( &si->si_cookieState->cs_mutex );
3111 
3112 #ifdef CHECK_CSN
3113 	for ( i=0; i<syncCookie->numcsns; i++ ) {
3114 		assert( !syn->ssyn_validate( syn, syncCookie->ctxcsn+i ));
3115 	}
3116 	for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3117 		assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
3118 	}
3119 #endif
3120 
3121 	/* clone the cookieState CSNs so we can Replace the whole thing */
3122 	mod.sml_numvals = si->si_cookieState->cs_num;
3123 	mod.sml_values = op->o_tmpalloc(( mod.sml_numvals+1 )*sizeof(struct berval), op->o_tmpmemctx );
3124 	for ( i=0; i<mod.sml_numvals; i++ )
3125 		mod.sml_values[i] = si->si_cookieState->cs_vals[i];
3126 	BER_BVZERO( &mod.sml_values[i] );
3127 
3128 	/* find any CSNs in the syncCookie that are newer than the cookieState */
3129 	for ( i=0; i<syncCookie->numcsns; i++ ) {
3130 		for ( j=0; j<si->si_cookieState->cs_num; j++ ) {
3131 			if ( syncCookie->sids[i] != si->si_cookieState->cs_sids[j] )
3132 				continue;
3133 			len = syncCookie->ctxcsn[i].bv_len;
3134 			if ( len > si->si_cookieState->cs_vals[j].bv_len )
3135 				len = si->si_cookieState->cs_vals[j].bv_len;
3136 			if ( memcmp( syncCookie->ctxcsn[i].bv_val,
3137 				si->si_cookieState->cs_vals[j].bv_val, len ) > 0 ) {
3138 				mod.sml_values[j] = syncCookie->ctxcsn[i];
3139 				changed = 1;
3140 				if ( BER_BVISNULL( &first ) ) {
3141 					first = syncCookie->ctxcsn[i];
3142 
3143 				} else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
3144 				{
3145 					first = syncCookie->ctxcsn[i];
3146 				}
3147 			}
3148 			break;
3149 		}
3150 		/* there was no match for this SID, it's a new CSN */
3151 		if ( j == si->si_cookieState->cs_num ) {
3152 			mod.sml_values = op->o_tmprealloc( mod.sml_values,
3153 				( mod.sml_numvals+2 )*sizeof(struct berval), op->o_tmpmemctx );
3154 			mod.sml_values[mod.sml_numvals++] = syncCookie->ctxcsn[i];
3155 			BER_BVZERO( &mod.sml_values[mod.sml_numvals] );
3156 			if ( BER_BVISNULL( &first ) ) {
3157 				first = syncCookie->ctxcsn[i];
3158 			} else if ( memcmp( syncCookie->ctxcsn[i].bv_val, first.bv_val, first.bv_len ) > 0 )
3159 			{
3160 				first = syncCookie->ctxcsn[i];
3161 			}
3162 			changed = 1;
3163 		}
3164 	}
3165 	/* Should never happen, ITS#5065 */
3166 	if ( BER_BVISNULL( &first ) || !changed ) {
3167 		ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3168 		op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
3169 		return 0;
3170 	}
3171 	op->o_bd = si->si_wbe;
3172 	slap_queue_csn( op, &first );
3173 
3174 	op->o_tag = LDAP_REQ_MODIFY;
3175 
3176 	cb.sc_response = null_callback;
3177 	cb.sc_private = si;
3178 
3179 	op->o_callback = &cb;
3180 	op->o_req_dn = si->si_contextdn;
3181 	op->o_req_ndn = si->si_contextdn;
3182 
3183 	/* update contextCSN */
3184 	op->o_dont_replicate = 1;
3185 
3186 	op->orm_modlist = &mod;
3187 	op->orm_no_opattrs = 1;
3188 	rc = op->o_bd->be_modify( op, &rs_modify );
3189 
3190 	if ( rs_modify.sr_err == LDAP_NO_SUCH_OBJECT &&
3191 		SLAP_SYNC_SUBENTRY( op->o_bd )) {
3192 		const char	*text;
3193 		char txtbuf[SLAP_TEXT_BUFLEN];
3194 		size_t textlen = sizeof txtbuf;
3195 		Entry *e = slap_create_context_csn_entry( op->o_bd, NULL );
3196 		rc = slap_mods2entry( &mod, &e, 0, 1, &text, txtbuf, textlen);
3197 		op->ora_e = e;
3198 		rc = op->o_bd->be_add( op, &rs_modify );
3199 		if ( e == op->ora_e )
3200 			be_entry_release_w( op, op->ora_e );
3201 	}
3202 
3203 	op->orm_no_opattrs = 0;
3204 	op->o_dont_replicate = 0;
3205 
3206 	if ( rs_modify.sr_err == LDAP_SUCCESS ) {
3207 		slap_sync_cookie_free( &si->si_syncCookie, 0 );
3208 		slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
3209 		/* If we replaced any old values */
3210 		for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3211 			if ( mod.sml_values[i].bv_val != si->si_cookieState->cs_vals[i].bv_val )
3212 					ber_bvreplace( &si->si_cookieState->cs_vals[i],
3213 						&mod.sml_values[i] );
3214 		}
3215 		/* Handle any added values */
3216 		if ( i < mod.sml_numvals ) {
3217 			si->si_cookieState->cs_num = mod.sml_numvals;
3218 			value_add( &si->si_cookieState->cs_vals, &mod.sml_values[i] );
3219 			free( si->si_cookieState->cs_sids );
3220 			si->si_cookieState->cs_sids = slap_parse_csn_sids(
3221 				si->si_cookieState->cs_vals, si->si_cookieState->cs_num, NULL );
3222 		}
3223 
3224 		si->si_cookieState->cs_age++;
3225 		si->si_cookieAge = si->si_cookieState->cs_age;
3226 	} else {
3227 		Debug( LDAP_DEBUG_ANY,
3228 			"syncrepl_updateCookie: %s be_modify failed (%d)\n",
3229 			si->si_ridtxt, rs_modify.sr_err, 0 );
3230 	}
3231 	ldap_pvt_thread_mutex_unlock( &si->si_cookieState->cs_mutex );
3232 
3233 	op->o_bd = be;
3234 	op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
3235 	BER_BVZERO( &op->o_csn );
3236 	if ( mod.sml_next ) slap_mods_free( mod.sml_next, 1 );
3237 	op->o_tmpfree( mod.sml_values, op->o_tmpmemctx );
3238 
3239 #ifdef CHECK_CSN
3240 	for ( i=0; i<si->si_cookieState->cs_num; i++ ) {
3241 		assert( !syn->ssyn_validate( syn, si->si_cookieState->cs_vals+i ));
3242 	}
3243 #endif
3244 
3245 	return rc;
3246 }
3247 
3248 /* Compare the attribute from the old entry to the one in the new
3249  * entry. The Modifications from the new entry will either be left
3250  * in place, or changed to an Add or Delete as needed.
3251  */
3252 static void
3253 attr_cmp( Operation *op, Attribute *old, Attribute *new,
3254 	Modifications ***mret, Modifications ***mcur )
3255 {
3256 	int i, j;
3257 	Modifications *mod, **modtail;
3258 
3259 	modtail = *mret;
3260 
3261 	if ( old ) {
3262 		int n, o, nn, no;
3263 		struct berval **adds, **dels;
3264 		/* count old and new */
3265 		for ( o=0; old->a_vals[o].bv_val; o++ ) ;
3266 		for ( n=0; new->a_vals[n].bv_val; n++ ) ;
3267 
3268 		/* there MUST be both old and new values */
3269 		assert( o != 0 );
3270 		assert( n != 0 );
3271 		j = 0;
3272 
3273 		adds = op->o_tmpalloc( sizeof(struct berval *) * n, op->o_tmpmemctx );
3274 		dels = op->o_tmpalloc( sizeof(struct berval *) * o, op->o_tmpmemctx );
3275 
3276 		for ( i=0; i<o; i++ ) dels[i] = &old->a_vals[i];
3277 		for ( i=0; i<n; i++ ) adds[i] = &new->a_vals[i];
3278 
3279 		nn = n; no = o;
3280 
3281 		for ( i=0; i<o; i++ ) {
3282 			for ( j=0; j<n; j++ ) {
3283 				if ( !adds[j] )
3284 					continue;
3285 				if ( bvmatch( dels[i], adds[j] ) ) {
3286 					no--;
3287 					nn--;
3288 					adds[j] = NULL;
3289 					dels[i] = NULL;
3290 					break;
3291 				}
3292 			}
3293 		}
3294 
3295 		/* Don't delete/add an objectClass, always use the replace op.
3296 		 * Modify would fail if provider has replaced entry with a new,
3297 		 * and the new explicitly includes a superior of a class that was
3298 		 * only included implicitly in the old entry.  Ref ITS#5517.
3299 		 *
3300 		 * Also use replace op if attr has no equality matching rule.
3301 		 * (ITS#5781)
3302 		 */
3303 		if ( ( nn || ( no > 0 && no < o ) ) &&
3304 			( old->a_desc == slap_schema.si_ad_objectClass ||
3305 			 !old->a_desc->ad_type->sat_equality ) )
3306 		{
3307 			no = o;
3308 		}
3309 
3310 		i = j;
3311 		/* all old values were deleted, just use the replace op */
3312 		if ( no == o ) {
3313 			i = j-1;
3314 		} else if ( no ) {
3315 		/* delete some values */
3316 			mod = ch_malloc( sizeof( Modifications ) );
3317 			mod->sml_op = LDAP_MOD_DELETE;
3318 			mod->sml_flags = 0;
3319 			mod->sml_desc = old->a_desc;
3320 			mod->sml_type = mod->sml_desc->ad_cname;
3321 			mod->sml_numvals = no;
3322 			mod->sml_values = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3323 			if ( old->a_vals != old->a_nvals ) {
3324 				mod->sml_nvalues = ch_malloc( ( no + 1 ) * sizeof(struct berval) );
3325 			} else {
3326 				mod->sml_nvalues = NULL;
3327 			}
3328 			j = 0;
3329 			for ( i = 0; i < o; i++ ) {
3330 				if ( !dels[i] ) continue;
3331 				ber_dupbv( &mod->sml_values[j], &old->a_vals[i] );
3332 				if ( mod->sml_nvalues ) {
3333 					ber_dupbv( &mod->sml_nvalues[j], &old->a_nvals[i] );
3334 				}
3335 				j++;
3336 			}
3337 			BER_BVZERO( &mod->sml_values[j] );
3338 			if ( mod->sml_nvalues ) {
3339 				BER_BVZERO( &mod->sml_nvalues[j] );
3340 			}
3341 			*modtail = mod;
3342 			modtail = &mod->sml_next;
3343 			i = j;
3344 		}
3345 		op->o_tmpfree( dels, op->o_tmpmemctx );
3346 		/* some values were added */
3347 		if ( nn && no < o ) {
3348 			mod = ch_malloc( sizeof( Modifications ) );
3349 			mod->sml_op = LDAP_MOD_ADD;
3350 			mod->sml_flags = 0;
3351 			mod->sml_desc = old->a_desc;
3352 			mod->sml_type = mod->sml_desc->ad_cname;
3353 			mod->sml_numvals = nn;
3354 			mod->sml_values = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3355 			if ( old->a_vals != old->a_nvals ) {
3356 				mod->sml_nvalues = ch_malloc( ( nn + 1 ) * sizeof(struct berval) );
3357 			} else {
3358 				mod->sml_nvalues = NULL;
3359 			}
3360 			j = 0;
3361 			for ( i = 0; i < n; i++ ) {
3362 				if ( !adds[i] ) continue;
3363 				ber_dupbv( &mod->sml_values[j], &new->a_vals[i] );
3364 				if ( mod->sml_nvalues ) {
3365 					ber_dupbv( &mod->sml_nvalues[j], &new->a_nvals[i] );
3366 				}
3367 				j++;
3368 			}
3369 			BER_BVZERO( &mod->sml_values[j] );
3370 			if ( mod->sml_nvalues ) {
3371 				BER_BVZERO( &mod->sml_nvalues[j] );
3372 			}
3373 			*modtail = mod;
3374 			modtail = &mod->sml_next;
3375 			i = j;
3376 		}
3377 		op->o_tmpfree( adds, op->o_tmpmemctx );
3378 	} else {
3379 		/* new attr, just use the new mod */
3380 		i = 0;
3381 		j = 1;
3382 	}
3383 	/* advance to next element */
3384 	mod = **mcur;
3385 	if ( mod ) {
3386 		if ( i != j ) {
3387 			**mcur = mod->sml_next;
3388 			*modtail = mod;
3389 			modtail = &mod->sml_next;
3390 		} else {
3391 			*mcur = &mod->sml_next;
3392 		}
3393 	}
3394 	*mret = modtail;
3395 }
3396 
3397 /* Generate a set of modifications to change the old entry into the
3398  * new one. On input ml is a list of modifications equivalent to
3399  * the new entry. It will be massaged and the result will be stored
3400  * in mods.
3401  */
3402 void syncrepl_diff_entry( Operation *op, Attribute *old, Attribute *new,
3403 	Modifications **mods, Modifications **ml, int is_ctx)
3404 {
3405 	Modifications **modtail = mods;
3406 
3407 	/* We assume that attributes are saved in the same order
3408 	 * in the remote and local databases. So if we walk through
3409 	 * the attributeDescriptions one by one they should match in
3410 	 * lock step. If not, look for an add or delete.
3411 	 */
3412 	while ( old && new )
3413 	{
3414 		/* If we've seen this before, use its mod now */
3415 		if ( new->a_flags & SLAP_ATTR_IXADD ) {
3416 			attr_cmp( op, NULL, new, &modtail, &ml );
3417 			new = new->a_next;
3418 			continue;
3419 		}
3420 		/* Skip contextCSN */
3421 		if ( is_ctx && old->a_desc ==
3422 			slap_schema.si_ad_contextCSN ) {
3423 			old = old->a_next;
3424 			continue;
3425 		}
3426 
3427 		if ( old->a_desc != new->a_desc ) {
3428 			Modifications *mod;
3429 			Attribute *tmp;
3430 
3431 			/* If it's just been re-added later,
3432 			 * remember that we've seen it.
3433 			 */
3434 			tmp = attr_find( new, old->a_desc );
3435 			if ( tmp ) {
3436 				tmp->a_flags |= SLAP_ATTR_IXADD;
3437 			} else {
3438 				/* If it's a new attribute, pull it in.
3439 				 */
3440 				tmp = attr_find( old, new->a_desc );
3441 				if ( !tmp ) {
3442 					attr_cmp( op, NULL, new, &modtail, &ml );
3443 					new = new->a_next;
3444 					continue;
3445 				}
3446 				/* Delete old attr */
3447 				mod = ch_malloc( sizeof( Modifications ) );
3448 				mod->sml_op = LDAP_MOD_DELETE;
3449 				mod->sml_flags = 0;
3450 				mod->sml_desc = old->a_desc;
3451 				mod->sml_type = mod->sml_desc->ad_cname;
3452 				mod->sml_numvals = 0;
3453 				mod->sml_values = NULL;
3454 				mod->sml_nvalues = NULL;
3455 				*modtail = mod;
3456 				modtail = &mod->sml_next;
3457 			}
3458 			old = old->a_next;
3459 			continue;
3460 		}
3461 		/* kludge - always update modifiersName so that it
3462 		 * stays co-located with the other mod opattrs. But only
3463 		 * if we know there are other valid mods.
3464 		 */
3465 		if ( *mods && ( old->a_desc == slap_schema.si_ad_modifiersName ||
3466 			old->a_desc == slap_schema.si_ad_modifyTimestamp ))
3467 			attr_cmp( op, NULL, new, &modtail, &ml );
3468 		else
3469 			attr_cmp( op, old, new, &modtail, &ml );
3470 		new = new->a_next;
3471 		old = old->a_next;
3472 	}
3473 	*modtail = *ml;
3474 	*ml = NULL;
3475 }
3476 
3477 static int
3478 dn_callback(
3479 	Operation*	op,
3480 	SlapReply*	rs )
3481 {
3482 	dninfo *dni = op->o_callback->sc_private;
3483 
3484 	if ( rs->sr_type == REP_SEARCH ) {
3485 		if ( !BER_BVISNULL( &dni->dn ) ) {
3486 			Debug( LDAP_DEBUG_ANY,
3487 				"dn_callback : consistency error - "
3488 				"entryUUID is not unique\n", 0, 0, 0 );
3489 		} else {
3490 			ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
3491 			ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
3492 			/* If there is a new entry, see if it differs from the old.
3493 			 * We compare the non-normalized values so that cosmetic changes
3494 			 * in the provider are always propagated.
3495 			 */
3496 			if ( dni->new_entry ) {
3497 				Modifications **modtail, **ml;
3498 				Attribute *old, *new;
3499 				struct berval old_rdn, new_rdn;
3500 				struct berval old_p, new_p;
3501 				int is_ctx, new_sup = 0;
3502 
3503 				/* If old entry is not a glue entry, make sure new entry
3504 				 * is actually newer than old entry
3505 				 */
3506 				if ( !is_entry_glue( rs->sr_entry )) {
3507 					old = attr_find( rs->sr_entry->e_attrs,
3508 						slap_schema.si_ad_entryCSN );
3509 					new = attr_find( dni->new_entry->e_attrs,
3510 						slap_schema.si_ad_entryCSN );
3511 					if ( new && old ) {
3512 						int rc;
3513 						ber_len_t len = old->a_vals[0].bv_len;
3514 						if ( len > new->a_vals[0].bv_len )
3515 							len = new->a_vals[0].bv_len;
3516 						rc = memcmp( old->a_vals[0].bv_val,
3517 							new->a_vals[0].bv_val, len );
3518 						if ( rc > 0 ) {
3519 							Debug( LDAP_DEBUG_SYNC,
3520 								"dn_callback : new entry is older than ours "
3521 								"%s ours %s, new %s\n",
3522 								rs->sr_entry->e_name.bv_val,
3523 								old->a_vals[0].bv_val,
3524 								new->a_vals[0].bv_val );
3525 							return LDAP_SUCCESS;
3526 						} else if ( rc == 0 ) {
3527 							Debug( LDAP_DEBUG_SYNC,
3528 								"dn_callback : entries have identical CSN "
3529 								"%s %s\n",
3530 								rs->sr_entry->e_name.bv_val,
3531 								old->a_vals[0].bv_val, 0 );
3532 							return LDAP_SUCCESS;
3533 						}
3534 					}
3535 				}
3536 
3537 				is_ctx = dn_match( &rs->sr_entry->e_nname,
3538 					&op->o_bd->be_nsuffix[0] );
3539 
3540 				/* Did the DN change?
3541 				 * case changes in the parent are ignored,
3542 				 * we only want to know if the RDN was
3543 				 * actually changed.
3544 				 */
3545 				dnRdn( &rs->sr_entry->e_name, &old_rdn );
3546 				dnRdn( &dni->new_entry->e_name, &new_rdn );
3547 				dnParent( &rs->sr_entry->e_nname, &old_p );
3548 				dnParent( &dni->new_entry->e_nname, &new_p );
3549 
3550 				new_sup = !dn_match( &old_p, &new_p );
3551 				if ( !dn_match( &old_rdn, &new_rdn ) || new_sup )
3552 				{
3553 					struct berval oldRDN, oldVal;
3554 					AttributeDescription *ad = NULL;
3555 					int oldpos, newpos;
3556 					Attribute *a;
3557 
3558 					dni->renamed = 1;
3559 					if ( new_sup )
3560 						dni->nnewSup = new_p;
3561 
3562 					/* See if the oldRDN was deleted */
3563 					dnRdn( &rs->sr_entry->e_nname, &oldRDN );
3564 					oldVal.bv_val = strchr(oldRDN.bv_val, '=') + 1;
3565 					oldVal.bv_len = oldRDN.bv_len - ( oldVal.bv_val -
3566 						oldRDN.bv_val );
3567 					oldRDN.bv_len -= oldVal.bv_len + 1;
3568 					slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
3569 					dni->oldDesc = ad;
3570 					for ( oldpos=0, a=rs->sr_entry->e_attrs;
3571 						a && a->a_desc != ad; oldpos++, a=a->a_next );
3572 					dni->oldNattr = a;
3573 					for ( newpos=0, a=dni->new_entry->e_attrs;
3574 						a && a->a_desc != ad; newpos++, a=a->a_next );
3575 					if ( !a || oldpos != newpos || attr_valfind( a,
3576 						SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH |
3577 						SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
3578 						SLAP_MR_VALUE_OF_SYNTAX,
3579 						&oldVal, NULL, op->o_tmpmemctx ) != LDAP_SUCCESS )
3580 					{
3581 						dni->delOldRDN = 1;
3582 					}
3583 					/* Get the newRDN's desc */
3584 					dnRdn( &dni->new_entry->e_nname, &oldRDN );
3585 					oldVal.bv_val = strchr(oldRDN.bv_val, '=');
3586 					oldRDN.bv_len = oldVal.bv_val - oldRDN.bv_val;
3587 					ad = NULL;
3588 					slap_bv2ad( &oldRDN, &ad, &rs->sr_text );
3589 					dni->newDesc = ad;
3590 
3591 					/* A ModDN has happened, but in Refresh mode other
3592 					 * changes may have occurred before we picked it up.
3593 					 * So fallthru to regular Modify processing.
3594 					 */
3595 				}
3596 
3597 				syncrepl_diff_entry( op, rs->sr_entry->e_attrs,
3598 					dni->new_entry->e_attrs, &dni->mods, dni->modlist,
3599 					is_ctx );
3600 			}
3601 		}
3602 	} else if ( rs->sr_type == REP_RESULT ) {
3603 		if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
3604 			Debug( LDAP_DEBUG_ANY,
3605 				"dn_callback : consistency error - "
3606 				"entryUUID is not unique\n", 0, 0, 0 );
3607 		}
3608 	}
3609 
3610 	return LDAP_SUCCESS;
3611 }
3612 
3613 static int
3614 nonpresent_callback(
3615 	Operation*	op,
3616 	SlapReply*	rs )
3617 {
3618 	syncinfo_t *si = op->o_callback->sc_private;
3619 	Attribute *a;
3620 	int count = 0;
3621 	struct berval* present_uuid = NULL;
3622 	struct nonpresent_entry *np_entry;
3623 
3624 	if ( rs->sr_type == REP_RESULT ) {
3625 		count = avl_free( si->si_presentlist, ch_free );
3626 		si->si_presentlist = NULL;
3627 
3628 	} else if ( rs->sr_type == REP_SEARCH ) {
3629 		if ( !( si->si_refreshDelete & NP_DELETE_ONE ) ) {
3630 			a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
3631 
3632 			if ( a ) {
3633 				present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
3634 					syncuuid_cmp );
3635 			}
3636 
3637 			if ( LogTest( LDAP_DEBUG_SYNC ) ) {
3638 				char buf[sizeof("rid=999 non")];
3639 
3640 				snprintf( buf, sizeof(buf), "%s %s", si->si_ridtxt,
3641 					present_uuid ? "" : "non" );
3642 
3643 				Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: %spresent UUID %s, dn %s\n",
3644 					buf, a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val );
3645 			}
3646 
3647 			if ( a == NULL ) return 0;
3648 		}
3649 
3650 		if ( present_uuid == NULL ) {
3651 			np_entry = (struct nonpresent_entry *)
3652 				ch_calloc( 1, sizeof( struct nonpresent_entry ) );
3653 			np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
3654 			np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
3655 			LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
3656 
3657 		} else {
3658 			avl_delete( &si->si_presentlist,
3659 				&a->a_nvals[0], syncuuid_cmp );
3660 			ch_free( present_uuid );
3661 		}
3662 	}
3663 	return LDAP_SUCCESS;
3664 }
3665 
3666 static int
3667 null_callback(
3668 	Operation*	op,
3669 	SlapReply*	rs )
3670 {
3671 	if ( rs->sr_err != LDAP_SUCCESS &&
3672 		rs->sr_err != LDAP_REFERRAL &&
3673 		rs->sr_err != LDAP_ALREADY_EXISTS &&
3674 		rs->sr_err != LDAP_NO_SUCH_OBJECT &&
3675 		rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
3676 	{
3677 		Debug( LDAP_DEBUG_ANY,
3678 			"null_callback : error code 0x%x\n",
3679 			rs->sr_err, 0, 0 );
3680 	}
3681 	return LDAP_SUCCESS;
3682 }
3683 
3684 static struct berval *
3685 slap_uuidstr_from_normalized(
3686 	struct berval* uuidstr,
3687 	struct berval* normalized,
3688 	void *ctx )
3689 {
3690 #if 0
3691 	struct berval *new;
3692 	unsigned char nibble;
3693 	int i, d = 0;
3694 
3695 	if ( normalized == NULL ) return NULL;
3696 	if ( normalized->bv_len != 16 ) return NULL;
3697 
3698 	if ( uuidstr ) {
3699 		new = uuidstr;
3700 	} else {
3701 		new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3702 		if ( new == NULL ) {
3703 			return NULL;
3704 		}
3705 	}
3706 
3707 	new->bv_len = 36;
3708 
3709 	if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3710 		if ( new != uuidstr ) {
3711 			slap_sl_free( new, ctx );
3712 		}
3713 		return NULL;
3714 	}
3715 
3716 	for ( i = 0; i < 16; i++ ) {
3717 		if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
3718 			new->bv_val[(i<<1)+d] = '-';
3719 			d += 1;
3720 		}
3721 
3722 		nibble = (normalized->bv_val[i] >> 4) & 0xF;
3723 		if ( nibble < 10 ) {
3724 			new->bv_val[(i<<1)+d] = nibble + '0';
3725 		} else {
3726 			new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
3727 		}
3728 
3729 		nibble = (normalized->bv_val[i]) & 0xF;
3730 		if ( nibble < 10 ) {
3731 			new->bv_val[(i<<1)+d+1] = nibble + '0';
3732 		} else {
3733 			new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
3734 		}
3735 	}
3736 
3737 	new->bv_val[new->bv_len] = '\0';
3738 	return new;
3739 #endif
3740 
3741 	struct berval	*new;
3742 	int		rc = 0;
3743 
3744 	if ( normalized == NULL ) return NULL;
3745 	if ( normalized->bv_len != 16 ) return NULL;
3746 
3747 	if ( uuidstr ) {
3748 		new = uuidstr;
3749 
3750 	} else {
3751 		new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
3752 		if ( new == NULL ) {
3753 			return NULL;
3754 		}
3755 	}
3756 
3757 	new->bv_len = 36;
3758 
3759 	if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
3760 		rc = 1;
3761 		goto done;
3762 	}
3763 
3764 	rc = lutil_uuidstr_from_normalized( normalized->bv_val,
3765 		normalized->bv_len, new->bv_val, new->bv_len + 1 );
3766 
3767 done:;
3768 	if ( rc == -1 ) {
3769 		if ( new != NULL ) {
3770 			if ( new->bv_val != NULL ) {
3771 				slap_sl_free( new->bv_val, ctx );
3772 			}
3773 
3774 			if ( new != uuidstr ) {
3775 				slap_sl_free( new, ctx );
3776 			}
3777 		}
3778 		new = NULL;
3779 
3780 	} else {
3781 		new->bv_len = rc;
3782 	}
3783 
3784 	return new;
3785 }
3786 
3787 static int
3788 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
3789 {
3790 	const struct berval *uuid1 = v_uuid1;
3791 	const struct berval *uuid2 = v_uuid2;
3792 	int rc = uuid1->bv_len - uuid2->bv_len;
3793 	if ( rc ) return rc;
3794 	return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
3795 }
3796 
3797 void
3798 syncinfo_free( syncinfo_t *sie, int free_all )
3799 {
3800 	syncinfo_t *si_next;
3801 
3802 	Debug( LDAP_DEBUG_TRACE, "syncinfo_free: %s\n",
3803 		sie->si_ridtxt, 0, 0 );
3804 
3805 	do {
3806 		si_next = sie->si_next;
3807 
3808 		if ( sie->si_ld ) {
3809 			if ( sie->si_conn ) {
3810 				connection_client_stop( sie->si_conn );
3811 				sie->si_conn = NULL;
3812 			}
3813 			ldap_unbind_ext( sie->si_ld, NULL, NULL );
3814 		}
3815 
3816 		if ( sie->si_re ) {
3817 			struct re_s		*re = sie->si_re;
3818 			sie->si_re = NULL;
3819 
3820 			ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
3821 			if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) )
3822 				ldap_pvt_runqueue_stoptask( &slapd_rq, re );
3823 			ldap_pvt_runqueue_remove( &slapd_rq, re );
3824 			ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
3825 		}
3826 
3827 		ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
3828 
3829 		bindconf_free( &sie->si_bindconf );
3830 
3831 		if ( sie->si_filterstr.bv_val ) {
3832 			ch_free( sie->si_filterstr.bv_val );
3833 		}
3834 		if ( sie->si_filter ) {
3835 			filter_free( sie->si_filter );
3836 		}
3837 		if ( sie->si_logfilterstr.bv_val ) {
3838 			ch_free( sie->si_logfilterstr.bv_val );
3839 		}
3840 		if ( sie->si_base.bv_val ) {
3841 			ch_free( sie->si_base.bv_val );
3842 		}
3843 		if ( sie->si_logbase.bv_val ) {
3844 			ch_free( sie->si_logbase.bv_val );
3845 		}
3846 		if ( sie->si_be && SLAP_SYNC_SUBENTRY( sie->si_be )) {
3847 			ch_free( sie->si_contextdn.bv_val );
3848 		}
3849 		if ( sie->si_attrs ) {
3850 			int i = 0;
3851 			while ( sie->si_attrs[i] != NULL ) {
3852 				ch_free( sie->si_attrs[i] );
3853 				i++;
3854 			}
3855 			ch_free( sie->si_attrs );
3856 		}
3857 		if ( sie->si_exattrs ) {
3858 			int i = 0;
3859 			while ( sie->si_exattrs[i] != NULL ) {
3860 				ch_free( sie->si_exattrs[i] );
3861 				i++;
3862 			}
3863 			ch_free( sie->si_exattrs );
3864 		}
3865 		if ( sie->si_anlist ) {
3866 			int i = 0;
3867 			while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
3868 				ch_free( sie->si_anlist[i].an_name.bv_val );
3869 				i++;
3870 			}
3871 			ch_free( sie->si_anlist );
3872 		}
3873 		if ( sie->si_exanlist ) {
3874 			int i = 0;
3875 			while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
3876 				ch_free( sie->si_exanlist[i].an_name.bv_val );
3877 				i++;
3878 			}
3879 			ch_free( sie->si_exanlist );
3880 		}
3881 		if ( sie->si_retryinterval ) {
3882 			ch_free( sie->si_retryinterval );
3883 		}
3884 		if ( sie->si_retrynum ) {
3885 			ch_free( sie->si_retrynum );
3886 		}
3887 		if ( sie->si_retrynum_init ) {
3888 			ch_free( sie->si_retrynum_init );
3889 		}
3890 		slap_sync_cookie_free( &sie->si_syncCookie, 0 );
3891 		if ( sie->si_presentlist ) {
3892 		    avl_free( sie->si_presentlist, ch_free );
3893 		}
3894 		while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist ) ) {
3895 			struct nonpresent_entry* npe;
3896 			npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
3897 			LDAP_LIST_REMOVE( npe, npe_link );
3898 			if ( npe->npe_name ) {
3899 				if ( npe->npe_name->bv_val ) {
3900 					ch_free( npe->npe_name->bv_val );
3901 				}
3902 				ch_free( npe->npe_name );
3903 			}
3904 			if ( npe->npe_nname ) {
3905 				if ( npe->npe_nname->bv_val ) {
3906 					ch_free( npe->npe_nname->bv_val );
3907 				}
3908 				ch_free( npe->npe_nname );
3909 			}
3910 			ch_free( npe );
3911 		}
3912 		if ( sie->si_cookieState ) {
3913 			sie->si_cookieState->cs_ref--;
3914 			if ( !sie->si_cookieState->cs_ref ) {
3915 				ch_free( sie->si_cookieState->cs_sids );
3916 				ber_bvarray_free( sie->si_cookieState->cs_vals );
3917 				ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_mutex );
3918 				ch_free( sie->si_cookieState->cs_psids );
3919 				ber_bvarray_free( sie->si_cookieState->cs_pvals );
3920 				ldap_pvt_thread_mutex_destroy( &sie->si_cookieState->cs_pmutex );
3921 				ch_free( sie->si_cookieState );
3922 			}
3923 		}
3924 		ch_free( sie );
3925 		sie = si_next;
3926 	} while ( free_all && si_next );
3927 }
3928 
3929 
3930 
3931 /* NOTE: used & documented in slapd.conf(5) */
3932 #define IDSTR			"rid"
3933 #define PROVIDERSTR		"provider"
3934 #define SCHEMASTR		"schemachecking"
3935 #define FILTERSTR		"filter"
3936 #define SEARCHBASESTR		"searchbase"
3937 #define SCOPESTR		"scope"
3938 #define ATTRSONLYSTR		"attrsonly"
3939 #define ATTRSSTR		"attrs"
3940 #define TYPESTR			"type"
3941 #define INTERVALSTR		"interval"
3942 #define RETRYSTR		"retry"
3943 #define SLIMITSTR		"sizelimit"
3944 #define TLIMITSTR		"timelimit"
3945 #define SYNCDATASTR		"syncdata"
3946 #define LOGBASESTR		"logbase"
3947 #define LOGFILTERSTR	"logfilter"
3948 
3949 /* FIXME: undocumented */
3950 #define EXATTRSSTR		"exattrs"
3951 #define MANAGEDSAITSTR		"manageDSAit"
3952 
3953 /* mandatory */
3954 enum {
3955 	GOT_RID			= 0x00000001U,
3956 	GOT_PROVIDER		= 0x00000002U,
3957 	GOT_SCHEMACHECKING	= 0x00000004U,
3958 	GOT_FILTER		= 0x00000008U,
3959 	GOT_SEARCHBASE		= 0x00000010U,
3960 	GOT_SCOPE		= 0x00000020U,
3961 	GOT_ATTRSONLY		= 0x00000040U,
3962 	GOT_ATTRS		= 0x00000080U,
3963 	GOT_TYPE		= 0x00000100U,
3964 	GOT_INTERVAL		= 0x00000200U,
3965 	GOT_RETRY		= 0x00000400U,
3966 	GOT_SLIMIT		= 0x00000800U,
3967 	GOT_TLIMIT		= 0x00001000U,
3968 	GOT_SYNCDATA		= 0x00002000U,
3969 	GOT_LOGBASE		= 0x00004000U,
3970 	GOT_LOGFILTER		= 0x00008000U,
3971 	GOT_EXATTRS		= 0x00010000U,
3972 	GOT_MANAGEDSAIT		= 0x00020000U,
3973 	GOT_BINDCONF		= 0x00040000U,
3974 
3975 /* check */
3976 	GOT_REQUIRED		= (GOT_RID|GOT_PROVIDER|GOT_SEARCHBASE)
3977 };
3978 
3979 static slap_verbmasks datamodes[] = {
3980 	{ BER_BVC("default"), SYNCDATA_DEFAULT },
3981 	{ BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
3982 	{ BER_BVC("changelog"), SYNCDATA_CHANGELOG },
3983 	{ BER_BVNULL, 0 }
3984 };
3985 
3986 static int
3987 parse_syncrepl_retry(
3988 	ConfigArgs	*c,
3989 	char		*arg,
3990 	syncinfo_t	*si )
3991 {
3992 	char **retry_list;
3993 	int j, k, n;
3994 	int use_default = 0;
3995 
3996 	char *val = arg + STRLENOF( RETRYSTR "=" );
3997 	if ( strcasecmp( val, "undefined" ) == 0 ) {
3998 		val = "3600 +";
3999 		use_default = 1;
4000 	}
4001 
4002 	retry_list = (char **) ch_calloc( 1, sizeof( char * ) );
4003 	retry_list[0] = NULL;
4004 
4005 	slap_str2clist( &retry_list, val, " ,\t" );
4006 
4007 	for ( k = 0; retry_list && retry_list[k]; k++ ) ;
4008 	n = k / 2;
4009 	if ( k % 2 ) {
4010 		snprintf( c->cr_msg, sizeof( c->cr_msg ),
4011 			"Error: incomplete syncrepl retry list" );
4012 		Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4013 		for ( k = 0; retry_list && retry_list[k]; k++ ) {
4014 			ch_free( retry_list[k] );
4015 		}
4016 		ch_free( retry_list );
4017 		return 1;
4018 	}
4019 	si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ) );
4020 	si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ) );
4021 	si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ) );
4022 	for ( j = 0; j < n; j++ ) {
4023 		unsigned long	t;
4024 		if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
4025 			snprintf( c->cr_msg, sizeof( c->cr_msg ),
4026 				"Error: invalid retry interval \"%s\" (#%d)",
4027 				retry_list[j*2], j );
4028 			Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4029 			/* do some cleanup */
4030 			return 1;
4031 		}
4032 		si->si_retryinterval[j] = (time_t)t;
4033 		if ( *retry_list[j*2+1] == '+' ) {
4034 			si->si_retrynum_init[j] = RETRYNUM_FOREVER;
4035 			si->si_retrynum[j] = RETRYNUM_FOREVER;
4036 			j++;
4037 			break;
4038 		} else {
4039 			if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
4040 					|| si->si_retrynum_init[j] <= 0 )
4041 			{
4042 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4043 					"Error: invalid initial retry number \"%s\" (#%d)",
4044 					retry_list[j*2+1], j );
4045 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4046 				/* do some cleanup */
4047 				return 1;
4048 			}
4049 			if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
4050 					|| si->si_retrynum[j] <= 0 )
4051 			{
4052 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4053 					"Error: invalid retry number \"%s\" (#%d)",
4054 					retry_list[j*2+1], j );
4055 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4056 				/* do some cleanup */
4057 				return 1;
4058 			}
4059 		}
4060 	}
4061 	if ( j < 1 || si->si_retrynum_init[j-1] != RETRYNUM_FOREVER ) {
4062 		Debug( LDAP_DEBUG_CONFIG,
4063 			"%s: syncrepl will eventually stop retrying; the \"retry\" parameter should end with a '+'.\n",
4064 			c->log, 0, 0 );
4065 	}
4066 
4067 	si->si_retrynum_init[j] = RETRYNUM_TAIL;
4068 	si->si_retrynum[j] = RETRYNUM_TAIL;
4069 	si->si_retryinterval[j] = 0;
4070 
4071 	for ( k = 0; retry_list && retry_list[k]; k++ ) {
4072 		ch_free( retry_list[k] );
4073 	}
4074 	ch_free( retry_list );
4075 	if ( !use_default ) {
4076 		si->si_got |= GOT_RETRY;
4077 	}
4078 
4079 	return 0;
4080 }
4081 
4082 static int
4083 parse_syncrepl_line(
4084 	ConfigArgs	*c,
4085 	syncinfo_t	*si )
4086 {
4087 	int	i;
4088 	char	*val;
4089 
4090 	for ( i = 1; i < c->argc; i++ ) {
4091 		if ( !strncasecmp( c->argv[ i ], IDSTR "=",
4092 					STRLENOF( IDSTR "=" ) ) )
4093 		{
4094 			int tmp;
4095 			/* '\0' string terminator accounts for '=' */
4096 			val = c->argv[ i ] + STRLENOF( IDSTR "=" );
4097 			if ( lutil_atoi( &tmp, val ) != 0 ) {
4098 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4099 					"Error: parse_syncrepl_line: "
4100 					"unable to parse syncrepl id \"%s\"", val );
4101 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4102 				return -1;
4103 			}
4104 			if ( tmp > SLAP_SYNC_RID_MAX || tmp < 0 ) {
4105 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4106 					"Error: parse_syncrepl_line: "
4107 					"syncrepl id %d is out of range [0..%d]", tmp, SLAP_SYNC_RID_MAX );
4108 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4109 				return -1;
4110 			}
4111 			si->si_rid = tmp;
4112 			sprintf( si->si_ridtxt, IDSTR "=%03d", si->si_rid );
4113 			si->si_got |= GOT_RID;
4114 		} else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
4115 					STRLENOF( PROVIDERSTR "=" ) ) )
4116 		{
4117 			val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
4118 			ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
4119 #ifdef HAVE_TLS
4120 			if ( ldap_is_ldaps_url( val ))
4121 				si->si_bindconf.sb_tls_do_init = 1;
4122 #endif
4123 			si->si_got |= GOT_PROVIDER;
4124 		} else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
4125 					STRLENOF( SCHEMASTR "=" ) ) )
4126 		{
4127 			val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
4128 			if ( !strncasecmp( val, "on", STRLENOF( "on" ) ) ) {
4129 				si->si_schemachecking = 1;
4130 			} else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
4131 				si->si_schemachecking = 0;
4132 			} else {
4133 				si->si_schemachecking = 1;
4134 			}
4135 			si->si_got |= GOT_SCHEMACHECKING;
4136 		} else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
4137 					STRLENOF( FILTERSTR "=" ) ) )
4138 		{
4139 			val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
4140 			if ( si->si_filterstr.bv_val )
4141 				ch_free( si->si_filterstr.bv_val );
4142 			ber_str2bv( val, 0, 1, &si->si_filterstr );
4143 			si->si_got |= GOT_FILTER;
4144 		} else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
4145 					STRLENOF( LOGFILTERSTR "=" ) ) )
4146 		{
4147 			val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
4148 			if ( si->si_logfilterstr.bv_val )
4149 				ch_free( si->si_logfilterstr.bv_val );
4150 			ber_str2bv( val, 0, 1, &si->si_logfilterstr );
4151 			si->si_got |= GOT_LOGFILTER;
4152 		} else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
4153 					STRLENOF( SEARCHBASESTR "=" ) ) )
4154 		{
4155 			struct berval	bv;
4156 			int		rc;
4157 
4158 			val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
4159 			if ( si->si_base.bv_val ) {
4160 				ch_free( si->si_base.bv_val );
4161 			}
4162 			ber_str2bv( val, 0, 0, &bv );
4163 			rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
4164 			if ( rc != LDAP_SUCCESS ) {
4165 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4166 					"Invalid base DN \"%s\": %d (%s)",
4167 					val, rc, ldap_err2string( rc ) );
4168 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4169 				return -1;
4170 			}
4171 			if ( !be_issubordinate( c->be, &si->si_base ) ) {
4172 				ch_free( si->si_base.bv_val );
4173 				BER_BVZERO( &si->si_base );
4174 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4175 					"Base DN \"%s\" is not within the database naming context",
4176 					val );
4177 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4178 				return -1;
4179 			}
4180 			si->si_got |= GOT_SEARCHBASE;
4181 		} else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
4182 					STRLENOF( LOGBASESTR "=" ) ) )
4183 		{
4184 			struct berval	bv;
4185 			int		rc;
4186 
4187 			val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
4188 			if ( si->si_logbase.bv_val ) {
4189 				ch_free( si->si_logbase.bv_val );
4190 			}
4191 			ber_str2bv( val, 0, 0, &bv );
4192 			rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
4193 			if ( rc != LDAP_SUCCESS ) {
4194 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4195 					"Invalid logbase DN \"%s\": %d (%s)",
4196 					val, rc, ldap_err2string( rc ) );
4197 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4198 				return -1;
4199 			}
4200 			si->si_got |= GOT_LOGBASE;
4201 		} else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
4202 					STRLENOF( SCOPESTR "=" ) ) )
4203 		{
4204 			int j;
4205 			val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
4206 			j = ldap_pvt_str2scope( val );
4207 			if ( j < 0 ) {
4208 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4209 					"Error: parse_syncrepl_line: "
4210 					"unknown scope \"%s\"", val);
4211 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4212 				return -1;
4213 			}
4214 			si->si_scope = j;
4215 			si->si_got |= GOT_SCOPE;
4216 		} else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
4217 					STRLENOF( ATTRSONLYSTR ) ) )
4218 		{
4219 			si->si_attrsonly = 1;
4220 			si->si_got |= GOT_ATTRSONLY;
4221 		} else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
4222 					STRLENOF( ATTRSSTR "=" ) ) )
4223 		{
4224 			val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
4225 			if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4226 				char *attr_fname;
4227 				attr_fname = ch_strdup( val + STRLENOF(":include:") );
4228 				si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
4229 				if ( si->si_anlist == NULL ) {
4230 					ch_free( attr_fname );
4231 					return -1;
4232 				}
4233 				si->si_anfile = attr_fname;
4234 			} else {
4235 				char *str, *s, *next;
4236 				const char *delimstr = " ,\t";
4237 				str = ch_strdup( val );
4238 				for ( s = ldap_pvt_strtok( str, delimstr, &next );
4239 						s != NULL;
4240 						s = ldap_pvt_strtok( NULL, delimstr, &next ) )
4241 				{
4242 					if ( strlen(s) == 1 && *s == '*' ) {
4243 						si->si_allattrs = 1;
4244 						val[ s - str ] = delimstr[0];
4245 					}
4246 					if ( strlen(s) == 1 && *s == '+' ) {
4247 						si->si_allopattrs = 1;
4248 						val [ s - str ] = delimstr[0];
4249 					}
4250 				}
4251 				ch_free( str );
4252 				si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
4253 				if ( si->si_anlist == NULL ) {
4254 					return -1;
4255 				}
4256 			}
4257 			si->si_got |= GOT_ATTRS;
4258 		} else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
4259 					STRLENOF( EXATTRSSTR "=" ) ) )
4260 		{
4261 			val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
4262 			if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
4263 				char *attr_fname;
4264 				attr_fname = ch_strdup( val + STRLENOF(":include:") );
4265 				si->si_exanlist = file2anlist(
4266 					si->si_exanlist, attr_fname, " ,\t" );
4267 				if ( si->si_exanlist == NULL ) {
4268 					ch_free( attr_fname );
4269 					return -1;
4270 				}
4271 				ch_free( attr_fname );
4272 			} else {
4273 				si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
4274 				if ( si->si_exanlist == NULL ) {
4275 					return -1;
4276 				}
4277 			}
4278 			si->si_got |= GOT_EXATTRS;
4279 		} else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
4280 					STRLENOF( TYPESTR "=" ) ) )
4281 		{
4282 			val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
4283 			if ( !strncasecmp( val, "refreshOnly",
4284 						STRLENOF("refreshOnly") ) )
4285 			{
4286 				si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
4287 			} else if ( !strncasecmp( val, "refreshAndPersist",
4288 						STRLENOF("refreshAndPersist") ) )
4289 			{
4290 				si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
4291 				si->si_interval = 60;
4292 			} else {
4293 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4294 					"Error: parse_syncrepl_line: "
4295 					"unknown sync type \"%s\"", val);
4296 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4297 				return -1;
4298 			}
4299 			si->si_got |= GOT_TYPE;
4300 		} else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
4301 					STRLENOF( INTERVALSTR "=" ) ) )
4302 		{
4303 			val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
4304 			if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
4305 				si->si_interval = 0;
4306 			} else if ( strchr( val, ':' ) != NULL ) {
4307 				char *next, *ptr = val;
4308 				int dd, hh, mm, ss;
4309 
4310 				dd = strtol( ptr, &next, 10 );
4311 				if ( next == ptr || next[0] != ':' || dd < 0 ) {
4312 					snprintf( c->cr_msg, sizeof( c->cr_msg ),
4313 						"Error: parse_syncrepl_line: "
4314 						"invalid interval \"%s\", unable to parse days", val );
4315 					Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4316 					return -1;
4317 				}
4318 				ptr = next + 1;
4319 				hh = strtol( ptr, &next, 10 );
4320 				if ( next == ptr || next[0] != ':' || hh < 0 || hh > 24 ) {
4321 					snprintf( c->cr_msg, sizeof( c->cr_msg ),
4322 						"Error: parse_syncrepl_line: "
4323 						"invalid interval \"%s\", unable to parse hours", val );
4324 					Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4325 					return -1;
4326 				}
4327 				ptr = next + 1;
4328 				mm = strtol( ptr, &next, 10 );
4329 				if ( next == ptr || next[0] != ':' || mm < 0 || mm > 60 ) {
4330 					snprintf( c->cr_msg, sizeof( c->cr_msg ),
4331 						"Error: parse_syncrepl_line: "
4332 						"invalid interval \"%s\", unable to parse minutes", val );
4333 					Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4334 					return -1;
4335 				}
4336 				ptr = next + 1;
4337 				ss = strtol( ptr, &next, 10 );
4338 				if ( next == ptr || next[0] != '\0' || ss < 0 || ss > 60 ) {
4339 					snprintf( c->cr_msg, sizeof( c->cr_msg ),
4340 						"Error: parse_syncrepl_line: "
4341 						"invalid interval \"%s\", unable to parse seconds", val );
4342 					Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4343 					return -1;
4344 				}
4345 				si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
4346 			} else {
4347 				unsigned long	t;
4348 
4349 				if ( lutil_parse_time( val, &t ) != 0 ) {
4350 					snprintf( c->cr_msg, sizeof( c->cr_msg ),
4351 						"Error: parse_syncrepl_line: "
4352 						"invalid interval \"%s\"", val );
4353 					Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4354 					return -1;
4355 				}
4356 				si->si_interval = (time_t)t;
4357 			}
4358 			if ( si->si_interval < 0 ) {
4359 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4360 					"Error: parse_syncrepl_line: "
4361 					"invalid interval \"%ld\"",
4362 					(long) si->si_interval);
4363 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4364 				return -1;
4365 			}
4366 			si->si_got |= GOT_INTERVAL;
4367 		} else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
4368 					STRLENOF( RETRYSTR "=" ) ) )
4369 		{
4370 			if ( parse_syncrepl_retry( c, c->argv[ i ], si ) ) {
4371 				return 1;
4372 			}
4373 		} else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
4374 					STRLENOF( MANAGEDSAITSTR "=" ) ) )
4375 		{
4376 			val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
4377 			if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
4378 				|| si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
4379 			{
4380 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4381 					"invalid manageDSAit value \"%s\".\n",
4382 					val );
4383 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4384 				return 1;
4385 			}
4386 			si->si_got |= GOT_MANAGEDSAIT;
4387 		} else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
4388 					STRLENOF( SLIMITSTR "=") ) )
4389 		{
4390 			val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
4391 			if ( strcasecmp( val, "unlimited" ) == 0 ) {
4392 				si->si_slimit = 0;
4393 
4394 			} else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
4395 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4396 					"invalid size limit value \"%s\".\n",
4397 					val );
4398 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4399 				return 1;
4400 			}
4401 			si->si_got |= GOT_SLIMIT;
4402 		} else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
4403 					STRLENOF( TLIMITSTR "=" ) ) )
4404 		{
4405 			val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
4406 			if ( strcasecmp( val, "unlimited" ) == 0 ) {
4407 				si->si_tlimit = 0;
4408 
4409 			} else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
4410 				snprintf( c->cr_msg, sizeof( c->cr_msg ),
4411 					"invalid time limit value \"%s\".\n",
4412 					val );
4413 				Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4414 				return 1;
4415 			}
4416 			si->si_got |= GOT_TLIMIT;
4417 		} else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
4418 					STRLENOF( SYNCDATASTR "=" ) ) )
4419 		{
4420 			val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
4421 			si->si_syncdata = verb_to_mask( val, datamodes );
4422 			si->si_got |= GOT_SYNCDATA;
4423 		} else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
4424 			snprintf( c->cr_msg, sizeof( c->cr_msg ),
4425 				"Error: parse_syncrepl_line: "
4426 				"unable to parse \"%s\"\n", c->argv[ i ] );
4427 			Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4428 			return -1;
4429 		}
4430 		si->si_got |= GOT_BINDCONF;
4431 	}
4432 
4433 	if ( ( si->si_got & GOT_REQUIRED ) != GOT_REQUIRED ) {
4434 		snprintf( c->cr_msg, sizeof( c->cr_msg ),
4435 			"Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
4436 			si->si_got & GOT_RID ? "" : " "IDSTR,
4437 			si->si_got & GOT_PROVIDER ? "" : " "PROVIDERSTR,
4438 			si->si_got & GOT_SEARCHBASE ? "" : " "SEARCHBASESTR );
4439 		Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->cr_msg, 0 );
4440 		return -1;
4441 	}
4442 
4443 	if ( !( si->si_got & GOT_RETRY ) ) {
4444 		Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": no retry defined, using default\n",
4445 			si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", 0 );
4446 		if ( si->si_retryinterval == NULL ) {
4447 			if ( parse_syncrepl_retry( c, "retry=undefined", si ) ) {
4448 				return 1;
4449 			}
4450 		}
4451 	}
4452 
4453 	si->si_filter = str2filter( si->si_filterstr.bv_val );
4454 	if ( si->si_filter == NULL ) {
4455 		Debug( LDAP_DEBUG_ANY, "syncrepl %s " SEARCHBASESTR "=\"%s\": unable to parse filter=\"%s\"\n",
4456 			si->si_ridtxt, c->be->be_suffix ? c->be->be_suffix[ 0 ].bv_val : "(null)", si->si_filterstr.bv_val );
4457 		return 1;
4458 	}
4459 
4460 	return 0;
4461 }
4462 
4463 static int
4464 add_syncrepl(
4465 	ConfigArgs *c )
4466 {
4467 	syncinfo_t *si;
4468 	int	rc = 0;
4469 
4470 	if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
4471 		snprintf( c->cr_msg, sizeof(c->cr_msg), "database %s does not support "
4472 			"operations required for syncrepl", c->be->be_type );
4473 		Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
4474 		return 1;
4475 	}
4476 	if ( BER_BVISEMPTY( &c->be->be_rootdn ) ) {
4477 		strcpy( c->cr_msg, "rootDN must be defined before syncrepl may be used" );
4478 		Debug( LDAP_DEBUG_ANY, "%s: %s\n", c->log, c->cr_msg, 0 );
4479 		return 1;
4480 	}
4481 	si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
4482 
4483 	if ( si == NULL ) {
4484 		Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
4485 		return 1;
4486 	}
4487 
4488 	si->si_bindconf.sb_tls = SB_TLS_OFF;
4489 	si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
4490 	si->si_schemachecking = 0;
4491 	ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
4492 		&si->si_filterstr );
4493 	si->si_base.bv_val = NULL;
4494 	si->si_scope = LDAP_SCOPE_SUBTREE;
4495 	si->si_attrsonly = 0;
4496 	si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
4497 	si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ) );
4498 	si->si_attrs = NULL;
4499 	si->si_allattrs = 0;
4500 	si->si_allopattrs = 0;
4501 	si->si_exattrs = NULL;
4502 	si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
4503 	si->si_interval = 86400;
4504 	si->si_retryinterval = NULL;
4505 	si->si_retrynum_init = NULL;
4506 	si->si_retrynum = NULL;
4507 	si->si_manageDSAit = 0;
4508 	si->si_tlimit = 0;
4509 	si->si_slimit = 0;
4510 
4511 	si->si_presentlist = NULL;
4512 	LDAP_LIST_INIT( &si->si_nonpresentlist );
4513 	ldap_pvt_thread_mutex_init( &si->si_mutex );
4514 
4515 	rc = parse_syncrepl_line( c, si );
4516 
4517 	if ( rc == 0 ) {
4518 		LDAPURLDesc *lud;
4519 
4520 		/* Must be LDAPv3 because we need controls */
4521 		switch ( si->si_bindconf.sb_version ) {
4522 		case 0:
4523 			/* not explicitly set */
4524 			si->si_bindconf.sb_version = LDAP_VERSION3;
4525 			break;
4526 		case 3:
4527 			/* explicitly set */
4528 			break;
4529 		default:
4530 			Debug( LDAP_DEBUG_ANY,
4531 				"version %d incompatible with syncrepl\n",
4532 				si->si_bindconf.sb_version, 0, 0 );
4533 			syncinfo_free( si, 0 );
4534 			return 1;
4535 		}
4536 
4537 		if ( ldap_url_parse( si->si_bindconf.sb_uri.bv_val, &lud )) {
4538 			snprintf( c->cr_msg, sizeof( c->cr_msg ),
4539 				"<%s> invalid URL", c->argv[0] );
4540 			Debug( LDAP_DEBUG_ANY, "%s: %s %s\n",
4541 				c->log, c->cr_msg, si->si_bindconf.sb_uri.bv_val );
4542 			return 1;
4543 		}
4544 
4545 		si->si_be = c->be;
4546 		if ( slapMode & SLAP_SERVER_MODE ) {
4547 			int isMe = 0;
4548 			/* check if consumer points to current server and database.
4549 			 * If so, ignore this configuration.
4550 			 */
4551 			if ( !SLAP_DBHIDDEN( c->be ) ) {
4552 				int i;
4553 				/* if searchbase doesn't match current DB suffix,
4554 				 * assume it's different
4555 				 */
4556 				for ( i=0; !BER_BVISNULL( &c->be->be_nsuffix[i] ); i++ ) {
4557 					if ( bvmatch( &si->si_base, &c->be->be_nsuffix[i] )) {
4558 						isMe = 1;
4559 						break;
4560 					}
4561 				}
4562 				/* if searchbase matches, see if URLs match */
4563 				if ( isMe && config_check_my_url( si->si_bindconf.sb_uri.bv_val,
4564 						lud ) == NULL )
4565 					isMe = 0;
4566 			}
4567 
4568 			if ( !isMe ) {
4569 				init_syncrepl( si );
4570 				ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4571 				si->si_re = ldap_pvt_runqueue_insert( &slapd_rq,
4572 					si->si_interval, do_syncrepl, si, "do_syncrepl",
4573 					si->si_ridtxt );
4574 				ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4575 				if ( si->si_re )
4576 					rc = config_sync_shadow( c ) ? -1 : 0;
4577 				else
4578 					rc = -1;
4579 			}
4580 		} else {
4581 			/* mirrormode still needs to see this flag in tool mode */
4582 			rc = config_sync_shadow( c ) ? -1 : 0;
4583 		}
4584 		ldap_free_urldesc( lud );
4585 	}
4586 
4587 #ifdef HAVE_TLS
4588 	/* Use main slapd defaults */
4589 	bindconf_tls_defaults( &si->si_bindconf );
4590 #endif
4591 	if ( rc < 0 ) {
4592 		Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
4593 		syncinfo_free( si, 0 );
4594 		return 1;
4595 	} else {
4596 		Debug( LDAP_DEBUG_CONFIG,
4597 			"Config: ** successfully added syncrepl %s \"%s\"\n",
4598 			si->si_ridtxt,
4599 			BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
4600 			"(null)" : si->si_bindconf.sb_uri.bv_val, 0 );
4601 		if ( c->be->be_syncinfo ) {
4602 			syncinfo_t *sip;
4603 
4604 			si->si_cookieState = c->be->be_syncinfo->si_cookieState;
4605 
4606 			/* add new syncrepl to end of list (same order as when deleting) */
4607 			for ( sip = c->be->be_syncinfo; sip->si_next; sip = sip->si_next );
4608 			sip->si_next = si;
4609 		} else {
4610 			si->si_cookieState = ch_calloc( 1, sizeof( cookie_state ));
4611 			ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_mutex );
4612 			ldap_pvt_thread_mutex_init( &si->si_cookieState->cs_pmutex );
4613 
4614 			c->be->be_syncinfo = si;
4615 		}
4616 		si->si_cookieState->cs_ref++;
4617 
4618 		si->si_next = NULL;
4619 
4620 		return 0;
4621 	}
4622 }
4623 
4624 static void
4625 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
4626 {
4627 	struct berval bc, uri, bs;
4628 	char buf[BUFSIZ*2], *ptr;
4629 	ber_len_t len;
4630 	int i;
4631 #	define WHATSLEFT	((ber_len_t) (&buf[sizeof( buf )] - ptr))
4632 
4633 	BER_BVZERO( bv );
4634 
4635 	/* temporarily inhibit bindconf from printing URI */
4636 	uri = si->si_bindconf.sb_uri;
4637 	BER_BVZERO( &si->si_bindconf.sb_uri );
4638 	si->si_bindconf.sb_version = 0;
4639 	bindconf_unparse( &si->si_bindconf, &bc );
4640 	si->si_bindconf.sb_uri = uri;
4641 	si->si_bindconf.sb_version = LDAP_VERSION3;
4642 
4643 	ptr = buf;
4644 	assert( si->si_rid >= 0 && si->si_rid <= SLAP_SYNC_RID_MAX );
4645 	len = snprintf( ptr, WHATSLEFT, IDSTR "=%03d " PROVIDERSTR "=%s",
4646 		si->si_rid, si->si_bindconf.sb_uri.bv_val );
4647 	if ( len >= sizeof( buf ) ) return;
4648 	ptr += len;
4649 	if ( !BER_BVISNULL( &bc ) ) {
4650 		if ( WHATSLEFT <= bc.bv_len ) {
4651 			free( bc.bv_val );
4652 			return;
4653 		}
4654 		ptr = lutil_strcopy( ptr, bc.bv_val );
4655 		free( bc.bv_val );
4656 	}
4657 	if ( !BER_BVISEMPTY( &si->si_filterstr ) ) {
4658 		if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
4659 		ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
4660 		ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
4661 		*ptr++ = '"';
4662 	}
4663 	if ( !BER_BVISNULL( &si->si_base ) ) {
4664 		if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
4665 		ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
4666 		ptr = lutil_strcopy( ptr, si->si_base.bv_val );
4667 		*ptr++ = '"';
4668 	}
4669 	if ( !BER_BVISEMPTY( &si->si_logfilterstr ) ) {
4670 		if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
4671 		ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
4672 		ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
4673 		*ptr++ = '"';
4674 	}
4675 	if ( !BER_BVISNULL( &si->si_logbase ) ) {
4676 		if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
4677 		ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
4678 		ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
4679 		*ptr++ = '"';
4680 	}
4681 	if ( ldap_pvt_scope2bv( si->si_scope, &bs ) == LDAP_SUCCESS ) {
4682 		if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + bs.bv_len ) return;
4683 		ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
4684 		ptr = lutil_strcopy( ptr, bs.bv_val );
4685 	}
4686 	if ( si->si_attrsonly ) {
4687 		if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
4688 		ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
4689 	}
4690 	if ( si->si_anfile ) {
4691 		if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
4692 		ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
4693 		ptr = lutil_strcopy( ptr, si->si_anfile );
4694 		*ptr++ = '"';
4695 	} else if ( si->si_allattrs || si->si_allopattrs ||
4696 		( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ) )
4697 	{
4698 		char *old;
4699 
4700 		if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
4701 		ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
4702 		old = ptr;
4703 		ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
4704 		if ( ptr == NULL ) return;
4705 		if ( si->si_allattrs ) {
4706 			if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
4707 			if ( old != ptr ) *ptr++ = ',';
4708 			*ptr++ = '*';
4709 		}
4710 		if ( si->si_allopattrs ) {
4711 			if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
4712 			if ( old != ptr ) *ptr++ = ',';
4713 			*ptr++ = '+';
4714 		}
4715 		*ptr++ = '"';
4716 	}
4717 	if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
4718 		if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
4719 		ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
4720 		ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
4721 		if ( ptr == NULL ) return;
4722 	}
4723 	if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
4724 	ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
4725 	ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
4726 
4727 	if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
4728 	ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
4729 	ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
4730 		"refreshAndPersist" : "refreshOnly" );
4731 
4732 	if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
4733 		int dd, hh, mm, ss;
4734 
4735 		dd = si->si_interval;
4736 		ss = dd % 60;
4737 		dd /= 60;
4738 		mm = dd % 60;
4739 		dd /= 60;
4740 		hh = dd % 24;
4741 		dd /= 24;
4742 		len = snprintf( ptr, WHATSLEFT, " %s=%02d:%02d:%02d:%02d",
4743 			INTERVALSTR, dd, hh, mm, ss );
4744 		if ( len >= WHATSLEFT ) return;
4745 		ptr += len;
4746 	}
4747 
4748 	if ( si->si_got & GOT_RETRY ) {
4749 		const char *space = "";
4750 		if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
4751 		ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
4752 		for (i=0; si->si_retryinterval[i]; i++) {
4753 			len = snprintf( ptr, WHATSLEFT, "%s%ld ", space,
4754 				(long) si->si_retryinterval[i] );
4755 			space = " ";
4756 			if ( WHATSLEFT - 1 <= len ) return;
4757 			ptr += len;
4758 			if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
4759 				*ptr++ = '+';
4760 			else {
4761 				len = snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
4762 				if ( WHATSLEFT <= len ) return;
4763 				ptr += len;
4764 			}
4765 		}
4766 		if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
4767 		*ptr++ = '"';
4768 	} else {
4769 		ptr = lutil_strcopy( ptr, " " RETRYSTR "=undefined" );
4770 	}
4771 
4772 	if ( si->si_slimit ) {
4773 		len = snprintf( ptr, WHATSLEFT, " " SLIMITSTR "=%d", si->si_slimit );
4774 		if ( WHATSLEFT <= len ) return;
4775 		ptr += len;
4776 	}
4777 
4778 	if ( si->si_tlimit ) {
4779 		len = snprintf( ptr, WHATSLEFT, " " TLIMITSTR "=%d", si->si_tlimit );
4780 		if ( WHATSLEFT <= len ) return;
4781 		ptr += len;
4782 	}
4783 
4784 	if ( si->si_syncdata ) {
4785 		if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
4786 			if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
4787 			ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
4788 			ptr = lutil_strcopy( ptr, bc.bv_val );
4789 		}
4790 	}
4791 	bc.bv_len = ptr - buf;
4792 	bc.bv_val = buf;
4793 	ber_dupbv( bv, &bc );
4794 }
4795 
4796 int
4797 syncrepl_config( ConfigArgs *c )
4798 {
4799 	if (c->op == SLAP_CONFIG_EMIT) {
4800 		if ( c->be->be_syncinfo ) {
4801 			struct berval bv;
4802 			syncinfo_t *si;
4803 
4804 			for ( si = c->be->be_syncinfo; si; si=si->si_next ) {
4805 				syncrepl_unparse( si, &bv );
4806 				ber_bvarray_add( &c->rvalue_vals, &bv );
4807 			}
4808 			return 0;
4809 		}
4810 		return 1;
4811 	} else if ( c->op == LDAP_MOD_DELETE ) {
4812 		int isrunning = 0;
4813 		if ( c->be->be_syncinfo ) {
4814 			syncinfo_t *si, **sip;
4815 			int i;
4816 
4817 			for ( sip = &c->be->be_syncinfo, i=0; *sip; i++ ) {
4818 				si = *sip;
4819 				if ( c->valx == -1 || i == c->valx ) {
4820 					*sip = si->si_next;
4821 					si->si_ctype = -1;
4822 					si->si_next = NULL;
4823 					/* If the task is currently active, we have to leave
4824 					 * it running. It will exit on its own. This will only
4825 					 * happen when running on the cn=config DB.
4826 					 */
4827 					if ( si->si_re ) {
4828 						if ( ldap_pvt_thread_mutex_trylock( &si->si_mutex )) {
4829 							isrunning = 1;
4830 						} else {
4831 							/* There is no active thread, but we must still
4832 							 * ensure that no thread is (or will be) queued
4833 							 * while we removes the task.
4834 							 */
4835 							struct re_s *re = si->si_re;
4836 							si->si_re = NULL;
4837 
4838 							if ( si->si_conn ) {
4839 								connection_client_stop( si->si_conn );
4840 								si->si_conn = NULL;
4841 							}
4842 
4843 							ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
4844 							if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ) ) {
4845 								ldap_pvt_runqueue_stoptask( &slapd_rq, re );
4846 								isrunning = 1;
4847 							}
4848 							ldap_pvt_runqueue_remove( &slapd_rq, re );
4849 							ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
4850 
4851 							if ( ldap_pvt_thread_pool_retract( &connection_pool,
4852 									re->routine, re ) > 0 )
4853 								isrunning = 0;
4854 
4855 							ldap_pvt_thread_mutex_unlock( &si->si_mutex );
4856 						}
4857 					}
4858 					if ( !isrunning ) {
4859 						syncinfo_free( si, 0 );
4860 					}
4861 					if ( i == c->valx )
4862 						break;
4863 				} else {
4864 					sip = &si->si_next;
4865 				}
4866 			}
4867 		}
4868 		if ( !c->be->be_syncinfo ) {
4869 			SLAP_DBFLAGS( c->be ) &= ~SLAP_DBFLAG_SHADOW_MASK;
4870 		}
4871 		return 0;
4872 	}
4873 	if ( SLAP_SLURP_SHADOW( c->be ) ) {
4874 		Debug(LDAP_DEBUG_ANY, "%s: "
4875 			"syncrepl: database already shadowed.\n",
4876 			c->log, 0, 0);
4877 		return(1);
4878 	} else {
4879 		return add_syncrepl( c );
4880 	}
4881 }
4882