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