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