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