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