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