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