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