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