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