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