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