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