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