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