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