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