]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
Single consumer context per database
[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-2005 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 "ldap_rq.h"
31
32 /* FIXME: for ldap_ld_free() */
33 #undef ldap_debug
34 #include "../../libraries/libldap/ldap-int.h"
35
36 #define SYNCREPL_STR    "syncreplxxx"
37 #define CN_STR  "cn="
38
39 static const struct berval slap_syncrepl_bvc = BER_BVC(SYNCREPL_STR);
40 static const struct berval slap_syncrepl_cn_bvc = BER_BVC(CN_STR SYNCREPL_STR);
41
42 static int syncuuid_cmp( const void *, const void * );
43 static void avl_ber_bvfree( void * );
44 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray );
45
46 /* callback functions */
47 static int dn_callback( struct slap_op *, struct slap_rep * );
48 static int nonpresent_callback( struct slap_op *, struct slap_rep * );
49 static int null_callback( struct slap_op *, struct slap_rep * );
50
51 static AttributeDescription *sync_descs[4];
52
53 void
54 init_syncrepl(syncinfo_t *si)
55 {
56         int i, j, k, l, n;
57         char **attrs, **exattrs;
58
59         if ( !sync_descs[0] ) {
60                 sync_descs[0] = slap_schema.si_ad_objectClass;
61                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
62                 sync_descs[2] = slap_schema.si_ad_entryCSN;
63                 sync_descs[3] = NULL;
64         }
65
66         if ( si->si_allattrs && si->si_allopattrs )
67                 attrs = NULL;
68         else
69                 attrs = anlist2attrs( si->si_anlist );
70
71         if ( attrs ) {
72                 if ( si->si_allattrs ) {
73                         i = 0;
74                         while ( attrs[i] ) {
75                                 if ( !is_at_operational( at_find( attrs[i] ))) {
76                                         for ( j = i; attrs[j] != NULL; j++ ) {
77                                                 if ( j == i )
78                                                         ch_free( attrs[i] );
79                                                 attrs[j] = attrs[j+1];
80                                         }
81                                 } else {
82                                         i++;
83                                 }
84                         }
85                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
86                         attrs[i] = ch_strdup("*");
87                         attrs[i + 1] = NULL;
88
89                 } else if ( si->si_allopattrs ) {
90                         i = 0;
91                         while ( attrs[i] ) {
92                                 if ( is_at_operational( at_find( attrs[i] ))) {
93                                         for ( j = i; attrs[j] != NULL; j++ ) {
94                                                 if ( j == i )
95                                                         ch_free( attrs[i] );
96                                                 attrs[j] = attrs[j+1];
97                                         }
98                                 } else {
99                                         i++;
100                                 }
101                         }
102                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
103                         attrs[i] = ch_strdup("+");
104                         attrs[i + 1] = NULL;
105                 }
106
107                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
108                         j = 0;
109                         while ( attrs[j] ) {
110                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val )) {
111                                         for ( k = j; attrs[k] != NULL; k++ ) {
112                                                 if ( k == j )
113                                                         ch_free( attrs[k] );
114                                                 attrs[k] = attrs[k+1];
115                                         }
116                                 } else {
117                                         j++;
118                                 }
119                         }
120                 }
121
122                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
123
124                 if ( si->si_allopattrs ) {
125                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ));
126                 } else {
127                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ));
128                 }
129
130                 if ( attrs == NULL ) {
131                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0,0,0 );
132                 }
133
134                 /* Add Attributes */
135                 if ( si->si_allopattrs ) {
136                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
137                 } else {
138                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
139                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
140                         }
141                 }
142                 attrs[ n ] = NULL;
143
144         } else {
145
146                 i = 0;
147                 if ( si->si_allattrs == si->si_allopattrs ) {
148                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
149                         attrs[i++] = ch_strdup( "*" );
150                         attrs[i++] = ch_strdup( "+" );
151                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
152                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
153                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
154                         attrs[i++] = ch_strdup( "*" );
155                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
156                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
157                         }
158                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
159                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
160                         attrs[i++] = ch_strdup( "+" );
161                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
162                 }
163                 attrs[i] = NULL;
164         }
165         
166         si->si_attrs = attrs;
167
168         exattrs = anlist2attrs( si->si_exanlist );
169
170         if ( exattrs ) {
171                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
172
173                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
174                         j = 0;
175                         while ( exattrs[j] != NULL ) {
176                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val )) {
177                                         for ( k = j; exattrs[k] != NULL; k++ ) {
178                                                 if ( k == j )
179                                                         ch_free( exattrs[k] );
180                                                 exattrs[k] = exattrs[k+1];
181                                         }
182                                 } else {
183                                         j++;
184                                 }
185                         }
186                 }
187
188                 for ( i = 0; exattrs[i] != NULL; i++ ) {
189                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
190                                 ObjectClass     *oc;
191                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
192                                         k = 0;
193                                         while ( oc->soc_required[k] ) {
194                                                 if ( !strcmp( exattrs[i],
195                                                          oc->soc_required[k]->sat_cname.bv_val )) {
196                                                         for ( l = i; exattrs[l]; l++ ) {
197                                                                 if ( l == i )
198                                                                         ch_free( exattrs[i] );
199                                                                 exattrs[l] = exattrs[l+1];
200                                                         }
201                                                 } else {
202                                                         k++;
203                                                 }
204                                         }
205                                 }
206                         }
207                 }
208
209                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
210
211                 if ( i != n )
212                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *));
213         }
214
215         si->si_exattrs = exattrs;       
216 }
217
218 static int
219 ldap_sync_search(
220         syncinfo_t *si,
221         void *ctx )
222 {
223         BerElementBuffer berbuf;
224         BerElement *ber = (BerElement *)&berbuf;
225         LDAPControl c[2], *ctrls[3];
226         struct timeval timeout;
227         ber_int_t       msgid;
228         int rc;
229
230         /* setup LDAP SYNC control */
231         ber_init2( ber, NULL, LBER_USE_DER );
232         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
233
234         if ( si->si_syncCookie.octet_str &&
235                 !BER_BVISNULL( &si->si_syncCookie.octet_str[0] ) )
236         {
237                 ber_printf( ber, "{eO}",
238                         abs(si->si_type),
239                         &si->si_syncCookie.octet_str[0] );
240         } else {
241                 ber_printf( ber, "{e}",
242                         abs(si->si_type) );
243         }
244
245         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 )) == LBER_ERROR ) {
246                 ber_free_buf( ber );
247                 return rc;
248         }
249
250         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
251         c[0].ldctl_iscritical = si->si_type < 0;
252         ctrls[0] = &c[0];
253
254         if ( si->si_authzId ) {
255                 c[1].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
256                 ber_str2bv( si->si_authzId, 0, 0, &c[1].ldctl_value );
257                 c[1].ldctl_iscritical = 1;
258                 ctrls[1] = &c[1];
259                 ctrls[2] = NULL;
260         } else {
261                 ctrls[1] = NULL;
262         }
263
264         timeout.tv_sec = si->si_tlimit;
265         timeout.tv_usec = 0;
266
267         rc = ldap_search_ext( si->si_ld, si->si_base.bv_val, si->si_scope,
268                 si->si_filterstr.bv_val, si->si_attrs, si->si_attrsonly,
269                 ctrls, NULL, si->si_tlimit > 0 ? &timeout : NULL,
270                 si->si_slimit, &msgid );
271         ber_free_buf( ber );
272         return rc;
273 }
274
275 static int
276 do_syncrep1(
277         Operation *op,
278         syncinfo_t *si )
279 {
280         int     rc;
281         int cmdline_cookie_found = 0;
282
283         char syncrepl_cbuf[sizeof(CN_STR SYNCREPL_STR)];
284         struct berval syncrepl_cn_bv;
285         struct sync_cookie      *sc = NULL;
286         struct berval   *psub;
287 #ifdef HAVE_TLS
288         void    *ssl;
289 #endif
290
291         psub = &si->si_be->be_nsuffix[0];
292
293         /* Init connection to master */
294         rc = ldap_initialize( &si->si_ld, si->si_provideruri );
295         if ( rc != LDAP_SUCCESS ) {
296                 Debug( LDAP_DEBUG_ANY,
297                         "do_syncrep1: ldap_initialize failed (%s)\n",
298                         si->si_provideruri, 0, 0 );
299                 return rc;
300         }
301
302         op->o_protocol = LDAP_VERSION3;
303         ldap_set_option( si->si_ld, LDAP_OPT_PROTOCOL_VERSION, &op->o_protocol );
304
305         /* Bind to master */
306
307         if ( si->si_tls ) {
308                 rc = ldap_start_tls_s( si->si_ld, NULL, NULL );
309                 if( rc != LDAP_SUCCESS ) {
310                         Debug( LDAP_DEBUG_ANY,
311                                 "%s: ldap_start_tls failed (%d)\n",
312                                 si->si_tls == SYNCINFO_TLS_CRITICAL ? "Error" : "Warning",
313                                 rc, 0 );
314                         if( si->si_tls == SYNCINFO_TLS_CRITICAL ) goto done;
315                 }
316         }
317
318         if ( si->si_bindmethod == LDAP_AUTH_SASL ) {
319 #ifdef HAVE_CYRUS_SASL
320                 void *defaults;
321
322                 if ( si->si_secprops != NULL ) {
323                         rc = ldap_set_option( si->si_ld,
324                                 LDAP_OPT_X_SASL_SECPROPS, si->si_secprops);
325
326                         if( rc != LDAP_OPT_SUCCESS ) {
327                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
328                                         "(%s,SECPROPS,\"%s\") failed!\n",
329                                         si->si_provideruri, si->si_secprops, 0 );
330                                 goto done;
331                         }
332                 }
333
334                 defaults = lutil_sasl_defaults( si->si_ld, si->si_saslmech,
335                         si->si_realm, si->si_authcId, si->si_passwd, si->si_authzId );
336
337                 rc = ldap_sasl_interactive_bind_s( si->si_ld,
338                                 si->si_binddn,
339                                 si->si_saslmech,
340                                 NULL, NULL,
341                                 LDAP_SASL_QUIET,
342                                 lutil_sasl_interact,
343                                 defaults );
344
345                 lutil_sasl_freedefs( defaults );
346
347                 /* FIXME: different error behaviors according to
348                  *      1) return code
349                  *      2) on err policy : exit, retry, backoff ...
350                  */
351                 if ( rc != LDAP_SUCCESS ) {
352                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
353                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
354                                 rc, 0, 0 );
355
356                         /* FIXME (see above comment) */
357                         /* if Kerberos credentials cache is not active, retry */
358                         if ( strcmp( si->si_saslmech, "GSSAPI" ) == 0 &&
359                                 rc == LDAP_LOCAL_ERROR )
360                         {
361                                 rc = LDAP_SERVER_DOWN;
362                         }
363
364                         goto done;
365                 }
366 #else /* HAVE_CYRUS_SASL */
367                 /* Should never get here, we trapped this at config time */
368                 assert(0);
369                 fprintf( stderr, "not compiled with SASL support\n" );
370                 rc = LDAP_OTHER;
371                 goto done;
372 #endif
373
374         } else {
375                 rc = ldap_bind_s( si->si_ld,
376                         si->si_binddn, si->si_passwd, si->si_bindmethod );
377                 if ( rc != LDAP_SUCCESS ) {
378                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
379                                 "ldap_bind_s failed (%d)\n", rc, 0, 0 );
380                         goto done;
381                 }
382         }
383
384         /* Set SSF to strongest of TLS, SASL SSFs */
385         op->o_sasl_ssf = 0;
386         op->o_tls_ssf = 0;
387         op->o_transport_ssf = 0;
388 #ifdef HAVE_TLS
389         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
390                 == LDAP_SUCCESS && ssl != NULL )
391         {
392                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
393         }
394 #endif /* HAVE_TLS */
395         ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &op->o_sasl_ssf );
396         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
397                 ?  op->o_sasl_ssf : op->o_tls_ssf;
398
399         /* get syncrepl cookie of shadow replica from subentry */
400         assert( si->si_rid < 1000 );
401         syncrepl_cn_bv.bv_val = syncrepl_cbuf;
402         syncrepl_cn_bv.bv_len = snprintf( syncrepl_cbuf, sizeof(syncrepl_cbuf),
403                 CN_STR "syncrepl%ld", si->si_rid );
404         build_new_dn( &op->o_req_ndn, psub, &syncrepl_cn_bv, op->o_tmpmemctx );
405         op->o_req_dn = op->o_req_ndn;
406
407         LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
408                 if ( si->si_rid == sc->rid ) {
409                         cmdline_cookie_found = 1;
410                         break;
411                 }
412         }
413
414         if ( cmdline_cookie_found ) {
415                 /* cookie is supplied in the command line */
416                 BerVarray cookie = NULL;
417                 struct berval cookie_bv;
418
419                 LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
420                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
421
422                 /* read stored cookie if it exists */
423                 backend_attribute( op, NULL, &op->o_req_ndn,
424                         slap_schema.si_ad_syncreplCookie, &cookie, ACL_READ );
425
426                 if ( !cookie ) {
427                         /* no stored cookie */
428                         if ( sc->ctxcsn == NULL ||
429                                  BER_BVISNULL( sc->ctxcsn ) ) {
430                                 /* if cmdline cookie does not have ctxcsn */
431                                 /* component, set it to an initial value */
432                                 slap_init_sync_cookie_ctxcsn( sc );
433                         }
434                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
435                         slap_sync_cookie_free( sc, 1 );
436                         sc = NULL;
437
438                 } else {
439                         /* stored cookie */
440                         struct berval newcookie = BER_BVNULL;
441                         ber_dupbv( &cookie_bv, &cookie[0] );
442                         ber_bvarray_add( &si->si_syncCookie.octet_str, &cookie_bv );
443                         slap_parse_sync_cookie( &si->si_syncCookie );
444                         ber_bvarray_free( si->si_syncCookie.octet_str );
445                         si->si_syncCookie.octet_str = NULL;
446                         ber_bvarray_free_x( cookie, op->o_tmpmemctx );
447                         if ( sc->ctxcsn != NULL ) {
448                                 /* command line cookie wins */
449                                 if ( si->si_syncCookie.ctxcsn ) {
450                                         ber_bvarray_free( si->si_syncCookie.ctxcsn );
451                                         si->si_syncCookie.ctxcsn = NULL;
452                                 }
453                                 ber_dupbv( &cookie_bv, &sc->ctxcsn[0] );
454                                 ber_bvarray_add( &si->si_syncCookie.ctxcsn, &cookie_bv );
455                         }
456                         if ( sc->rid != -1 ) {
457                                 /* command line cookie wins */
458                                 si->si_syncCookie.rid = sc->rid;
459                         }
460                         slap_sync_cookie_free( sc, 1 );
461                         sc = NULL;
462                         slap_compose_sync_cookie( NULL, &newcookie,
463                                         &si->si_syncCookie.ctxcsn[0],
464                                         si->si_syncCookie.rid );
465                         ber_bvarray_add( &si->si_syncCookie.octet_str, &newcookie );
466                 }
467
468         } else {
469                 /* no command line cookie is specified */
470                 if ( si->si_syncCookie.octet_str == NULL ) {
471                         BerVarray cookie = NULL;
472                         struct berval cookie_bv;
473                         /* try to read stored cookie */
474                         backend_attribute( op, NULL, &op->o_req_ndn,
475                                 slap_schema.si_ad_syncreplCookie, &cookie, ACL_READ );
476                         if ( cookie ) {
477                                 ber_dupbv( &cookie_bv, &cookie[0] );
478                                 ber_bvarray_add( &si->si_syncCookie.octet_str, &cookie_bv );
479                                 slap_parse_sync_cookie( &si->si_syncCookie );
480                                 ber_bvarray_free_x( cookie, op->o_tmpmemctx );
481                         }
482                 }
483         }
484
485         rc = ldap_sync_search( si, op->o_tmpmemctx );
486
487         if( rc != LDAP_SUCCESS ) {
488                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
489                         "ldap_search_ext: %s (%d)\n", ldap_err2string( rc ), rc, 0 );
490         }
491
492 done:
493         if ( rc ) {
494                 if ( si->si_ld ) {
495                         ldap_unbind( si->si_ld );
496                         si->si_ld = NULL;
497                 }
498         }
499
500         slap_sl_free( op->o_req_ndn.bv_val, op->o_tmpmemctx );
501
502         return rc;
503 }
504
505 static int
506 do_syncrep2(
507         Operation *op,
508         syncinfo_t *si )
509 {
510         LDAPControl     **rctrls = NULL;
511         LDAPControl     *rctrlp;
512
513         BerElementBuffer berbuf;
514         BerElement      *ber = (BerElement *)&berbuf;
515
516         LDAPMessage     *res = NULL;
517         LDAPMessage     *msg = NULL;
518
519         char            *retoid = NULL;
520         struct berval   *retdata = NULL;
521
522         Entry           *entry = NULL;
523
524         int             syncstate;
525         struct berval   syncUUID = BER_BVNULL;
526         struct sync_cookie      syncCookie = { NULL };
527         struct sync_cookie      syncCookie_req = { NULL };
528         struct berval           cookie = BER_BVNULL;
529
530         int     rc, err, i;
531         ber_len_t       len;
532
533         int rc_efree = 1;
534
535         struct berval   *psub;
536         Modifications   *modlist = NULL;
537
538         const char              *text;
539         int                             match;
540
541         struct timeval *tout_p = NULL;
542         struct timeval tout = { 0, 0 };
543
544         int             refreshDeletes = 0;
545         int             refreshDone = 1;
546         BerVarray syncUUIDs = NULL;
547         ber_tag_t si_tag;
548
549         if ( slapd_shutdown ) {
550                 rc = -2;
551                 goto done;
552         }
553
554         ber_init2( ber, NULL, LBER_USE_DER );
555         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
556
557         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2\n", 0, 0, 0 );
558
559         psub = &si->si_be->be_nsuffix[0];
560
561         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
562
563         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
564                 tout_p = &tout;
565         } else {
566                 tout_p = NULL;
567         }
568
569         while (( rc = ldap_result( si->si_ld, LDAP_RES_ANY, LDAP_MSG_ONE,
570                 tout_p, &res )) > 0 )
571         {
572                 if ( slapd_shutdown ) {
573                         rc = -2;
574                         goto done;
575                 }
576                 for( msg = ldap_first_message( si->si_ld, res );
577                         msg != NULL;
578                         msg = ldap_next_message( si->si_ld, msg ) )
579                 {
580                         switch( ldap_msgtype( msg ) ) {
581                         case LDAP_RES_SEARCH_ENTRY:
582                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
583                                 /* we can't work without the control */
584                                 if ( !rctrls ) {
585                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: "
586                                                 "got search entry without "
587                                                 "control\n", 0, 0, 0 );
588                                         rc = -1;
589                                         goto done;
590                                 }
591                                 rctrlp = *rctrls;
592                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
593                                 ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
594                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
595                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
596                                         if ( !BER_BVISNULL( &cookie ) ) {
597                                                 struct berval tmp_bv;
598                                                 ber_dupbv( &tmp_bv, &cookie );
599                                                 ber_bvarray_add( &syncCookie.octet_str, &tmp_bv );
600                                         }
601                                         if ( syncCookie.octet_str &&
602                                                         !BER_BVISNULL( &syncCookie.octet_str[0] ) )
603                                         {
604                                                 slap_parse_sync_cookie( &syncCookie );
605                                         }
606                                 }
607                                 if ( syncrepl_message_to_entry( si, op, msg,
608                                         &modlist, &entry, syncstate ) == LDAP_SUCCESS ) {
609                                         rc_efree = syncrepl_entry( si, op, entry, &modlist,
610                                                 syncstate, &syncUUID, &syncCookie_req, syncCookie.ctxcsn );
611                                         if ( syncCookie.octet_str &&
612                                                 !BER_BVISNULL( &syncCookie.octet_str[0] ) )
613                                         {
614                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
615                                         }
616                                 }
617                                 ldap_controls_free( rctrls );
618                                 if ( modlist ) {
619                                         slap_mods_free( modlist );
620                                 }
621                                 if ( rc_efree && entry ) {
622                                         entry_free( entry );
623                                 }
624                                 entry = NULL;
625                                 break;
626
627                         case LDAP_RES_SEARCH_REFERENCE:
628                                 Debug( LDAP_DEBUG_ANY,
629                                         "do_syncrep2: reference received error\n", 0, 0, 0 );
630                                 break;
631
632                         case LDAP_RES_SEARCH_RESULT:
633                                 Debug( LDAP_DEBUG_SYNC,
634                                         "do_syncrep2: LDAP_RES_SEARCH_RESULT\n", 0, 0, 0 );
635                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
636                                         &rctrls, 0 );
637                                 if ( rctrls ) {
638                                         rctrlp = *rctrls;
639                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
640
641                                         ber_scanf( ber, "{" /*"}"*/);
642                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
643                                                 ber_scanf( ber, "m", &cookie );
644                                                 if ( !BER_BVISNULL( &cookie ) ) {
645                                                         struct berval tmp_bv;
646                                                         ber_dupbv( &tmp_bv, &cookie );
647                                                         ber_bvarray_add( &syncCookie.octet_str, &tmp_bv);
648                                                 }
649                                                 if ( syncCookie.octet_str &&
650                                                         !BER_BVISNULL( &syncCookie.octet_str[0] ) )
651                                                 {
652                                                         slap_parse_sync_cookie( &syncCookie );
653                                                 }
654                                         }
655                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
656                                         {
657                                                 ber_scanf( ber, "b", &refreshDeletes );
658                                         }
659                                         ber_scanf( ber, /*"{"*/ "}" );
660                                 }
661                                 if ( syncCookie_req.ctxcsn == NULL ) {
662                                         match = -1;
663                                 } else if ( syncCookie.ctxcsn == NULL ) {
664                                         match = 1;
665                                 } else {
666                                         value_match( &match, slap_schema.si_ad_entryCSN,
667                                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
668                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
669                                                 &syncCookie_req.ctxcsn[0], &syncCookie.ctxcsn[0],
670                                                 &text );
671                                 }
672                                 if ( syncCookie.octet_str && !BER_BVISNULL( syncCookie.octet_str ) &&
673                                         match < 0 && err == LDAP_SUCCESS )
674                                 {
675                                         syncrepl_updateCookie( si, op, psub, &syncCookie );
676                                 }
677                                 if ( rctrls ) {
678                                         ldap_controls_free( rctrls );
679                                 }
680                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
681                                         /* FIXME : different error behaviors according to
682                                          *      1) err code : LDAP_BUSY ...
683                                          *      2) on err policy : stop service, stop sync, retry
684                                          */
685                                         if ( refreshDeletes == 0 && match < 0 &&
686                                                 err == LDAP_SUCCESS )
687                                         {
688                                                 syncrepl_del_nonpresent( op, si, NULL );
689                                         } else {
690                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
691                                                 si->si_presentlist = NULL;
692                                         }
693                                 }
694                                 rc = -2;
695                                 goto done;
696                                 break;
697
698                         case LDAP_RES_INTERMEDIATE:
699                                 rc = ldap_parse_intermediate( si->si_ld, msg,
700                                         &retoid, &retdata, NULL, 0 );
701                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
702                                         ber_init2( ber, retdata, LBER_USE_DER );
703
704                                         switch ( si_tag = ber_peek_tag( ber, &len )) {
705                                         ber_tag_t tag;
706                                         case LDAP_TAG_SYNC_NEW_COOKIE:
707                                                 Debug( LDAP_DEBUG_SYNC,
708                                                         "do_syncrep2: %s - %s%s\n", 
709                                                         "LDAP_RES_INTERMEDIATE", 
710                                                         "NEW_COOKIE", "\n" );
711                                                 ber_scanf( ber, "tm", &tag, &cookie );
712                                                 break;
713                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
714                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
715                                                 Debug( LDAP_DEBUG_SYNC,
716                                                         "do_syncrep2: %s - %s%s\n", 
717                                                         "LDAP_RES_INTERMEDIATE", 
718                                                         si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
719                                                         "REFRESH_PRESENT" : "REFRESH_DELETE",
720                                                         "\n" );
721                                                 if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
722                                                         si->si_refreshDelete = 1;
723                                                 } else {
724                                                         si->si_refreshPresent = 1;
725                                                 }
726                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
727                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
728                                                 {
729                                                         ber_scanf( ber, "m", &cookie );
730                                                         if ( !BER_BVISNULL( &cookie ) ) {
731                                                                 struct berval tmp_bv;
732                                                                 ber_dupbv( &tmp_bv, &cookie );
733                                                                 ber_bvarray_add( &syncCookie.octet_str,
734                                                                         &tmp_bv);
735                                                         }
736                                                         if ( syncCookie.octet_str &&
737                                                                 !BER_BVISNULL( &syncCookie.octet_str[0] ) )
738                                                         {
739                                                                 slap_parse_sync_cookie( &syncCookie );
740                                                         }
741                                                 }
742                                                 if ( ber_peek_tag( ber, &len ) ==
743                                                         LDAP_TAG_REFRESHDONE )
744                                                 {
745                                                         ber_scanf( ber, "b", &refreshDone );
746                                                 }
747                                                 ber_scanf( ber, /*"{"*/ "}" );
748                                                 break;
749                                         case LDAP_TAG_SYNC_ID_SET:
750                                                 Debug( LDAP_DEBUG_SYNC,
751                                                         "do_syncrep2: %s - %s%s\n", 
752                                                         "LDAP_RES_INTERMEDIATE", 
753                                                         "SYNC_ID_SET",
754                                                         "\n" );
755                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
756                                                 if ( ber_peek_tag( ber, &len ) ==
757                                                         LDAP_TAG_SYNC_COOKIE )
758                                                 {
759                                                         ber_scanf( ber, "m", &cookie );
760                                                         if ( !BER_BVISNULL( &cookie ) ) {
761                                                                 struct berval tmp_bv;
762                                                                 ber_dupbv( &tmp_bv, &cookie );
763                                                                 ber_bvarray_add( &syncCookie.octet_str,
764                                                                         &tmp_bv );
765                                                         }
766                                                         if ( syncCookie.octet_str &&
767                                                                         !BER_BVISNULL( &syncCookie.octet_str[0] ) )
768                                                         {
769                                                                 slap_parse_sync_cookie( &syncCookie );
770                                                         }
771                                                 }
772                                                 if ( ber_peek_tag( ber, &len ) ==
773                                                         LDAP_TAG_REFRESHDELETES )
774                                                 {
775                                                         ber_scanf( ber, "b", &refreshDeletes );
776                                                 }
777                                                 ber_scanf( ber, "[W]", &syncUUIDs );
778                                                 ber_scanf( ber, /*"{"*/ "}" );
779                                                 if ( refreshDeletes ) {
780                                                         syncrepl_del_nonpresent( op, si, syncUUIDs );
781                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
782                                                 } else {
783                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
784                                                                 struct berval *syncuuid_bv;
785                                                                 syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
786                                                                 slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
787                                                                 avl_insert( &si->si_presentlist,
788                                                                         (caddr_t) syncuuid_bv,
789                                                                         syncuuid_cmp, avl_dup_error );
790                                                         }
791                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
792                                                 }
793                                                 break;
794                                         default:
795                                                 Debug( LDAP_DEBUG_ANY,
796                                                         "do_syncrep2 : unknown syncinfo tag (%ld)\n",
797                                                 (long) si_tag, 0, 0 );
798                                                 ldap_memfree( retoid );
799                                                 ber_bvfree( retdata );
800                                                 continue;
801                                         }
802
803                                         if ( syncCookie_req.ctxcsn == NULL ) {
804                                                 match = -1;
805                                         } else if ( syncCookie.ctxcsn == NULL ) {
806                                                 match = 1;
807                                         } else {
808                                                 value_match( &match, slap_schema.si_ad_entryCSN,
809                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
810                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
811                                                         &syncCookie_req.ctxcsn[0],
812                                                         &syncCookie.ctxcsn[0], &text );
813                                         }
814
815                                         if ( syncCookie.ctxcsn && !BER_BVISNULL( &syncCookie.ctxcsn[0] ) &&
816                                                 match < 0 )
817                                         {
818                                                 syncrepl_updateCookie( si, op, psub, &syncCookie);
819                                         }
820
821                                         if ( si->si_refreshPresent == 1 ) {
822                                                 if ( match < 0 ) {
823                                                         syncrepl_del_nonpresent( op, si, NULL );
824                                                 }
825                                         } 
826
827                                         ldap_memfree( retoid );
828                                         ber_bvfree( retdata );
829                                         break;
830
831                                 } else {
832                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
833                                                 "unknown intermediate response (%d)\n",
834                                                 rc, 0, 0 );
835                                         ldap_memfree( retoid );
836                                         ber_bvfree( retdata );
837                                         break;
838                                 }
839                                 break;
840
841                         default:
842                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
843                                         "unknown message\n", 0, 0, 0 );
844                                 break;
845
846                         }
847                         if ( syncCookie.octet_str ) {
848                                 slap_sync_cookie_free( &syncCookie_req, 0 );
849                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
850                                 slap_sync_cookie_free( &syncCookie, 0 );
851                         }
852                 }
853                 ldap_msgfree( res );
854                 res = NULL;
855         }
856
857         if ( rc == -1 ) {
858                 const char *errstr;
859
860                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
861                 errstr = ldap_err2string( rc );
862                 
863                 Debug( LDAP_DEBUG_ANY,
864                         "do_syncrep2 : %s\n", errstr, 0, 0 );
865         }
866
867 done:
868         slap_sync_cookie_free( &syncCookie, 0 );
869         slap_sync_cookie_free( &syncCookie_req, 0 );
870
871         if ( res ) ldap_msgfree( res );
872
873         if ( rc && si->si_ld ) {
874                 ldap_unbind( si->si_ld );
875                 si->si_ld = NULL;
876         }
877
878         return rc;
879 }
880
881 void *
882 do_syncrepl(
883         void    *ctx,
884         void    *arg )
885 {
886         struct re_s* rtask = arg;
887         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
888         Connection conn = {0};
889         char opbuf[OPERATION_BUFFER_SIZE];
890         Operation *op;
891         int rc = LDAP_SUCCESS;
892         int first = 0;
893         int dostop = 0;
894         ber_socket_t s;
895         int i, defer = 1;
896         Backend *be;
897
898         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
899
900         if ( si == NULL )
901                 return NULL;
902
903         switch( abs( si->si_type )) {
904         case LDAP_SYNC_REFRESH_ONLY:
905         case LDAP_SYNC_REFRESH_AND_PERSIST:
906                 break;
907         default:
908                 return NULL;
909         }
910
911         if ( slapd_shutdown ) {
912                 if ( si->si_ld ) {
913                         ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
914                         connection_client_stop( s );
915                         ldap_unbind( si->si_ld );
916                         si->si_ld = NULL;
917                 }
918                 return NULL;
919         }
920
921         op = (Operation *)opbuf;
922         connection_fake_init( &conn, op, ctx );
923
924         /* use global malloc for now */
925         op->o_tmpmemctx = NULL;
926         op->o_tmpmfuncs = &ch_mfuncs;
927
928         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
929         op->o_bd = be = si->si_be;
930         op->o_dn = op->o_bd->be_rootdn;
931         op->o_ndn = op->o_bd->be_rootndn;
932
933         /* Establish session, do search */
934         if ( !si->si_ld ) {
935                 first = 1;
936                 si->si_refreshDelete = 0;
937                 si->si_refreshPresent = 0;
938                 rc = do_syncrep1( op, si );
939         }
940
941         /* Process results */
942         if ( rc == LDAP_SUCCESS ) {
943                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
944
945                 rc = do_syncrep2( op, si );
946
947                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
948                         /* If we succeeded, enable the connection for further listening.
949                          * If we failed, tear down the connection and reschedule.
950                          */
951                         if ( rc == LDAP_SUCCESS ) {
952                                 if ( first ) {
953                                         rc = connection_client_setup( s, do_syncrepl, arg );
954                                 } else {
955                                         connection_client_enable( s );
956                                 } 
957                         } else if ( !first ) {
958                                 dostop = 1;
959                         }
960                 } else {
961                         if ( rc == -2 ) rc = 0;
962                 }
963         }
964
965         /* At this point, we have 4 cases:
966          * 1) for any hard failure, give up and remove this task
967          * 2) for ServerDown, reschedule this task to run
968          * 3) for Refresh and Success, reschedule to run
969          * 4) for Persist and Success, reschedule to defer
970          */
971         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
972
973         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
974                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
975         }
976
977         if ( dostop ) {
978                 connection_client_stop( s );
979         }
980
981         if ( rc == LDAP_SUCCESS ) {
982                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
983                         defer = 0;
984                 }
985                 rtask->interval.tv_sec = si->si_interval;
986                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
987                 if ( si->si_retrynum ) {
988                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
989                                 si->si_retrynum[i] = si->si_retrynum_init[i];
990                         }
991                         si->si_retrynum[i] = -2;
992                 }
993         } else {
994                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
995                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
996                                 break;
997                 }
998
999                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
1000                         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1001                 } else if ( si->si_retrynum[i] >= -1 ) {
1002                         if ( si->si_retrynum[i] > 0 )
1003                                 si->si_retrynum[i]--;
1004                         rtask->interval.tv_sec = si->si_retryinterval[i];
1005                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1006                         slap_wake_listener();
1007                 }
1008         }
1009         
1010         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1011
1012         return NULL;
1013 }
1014
1015 int
1016 syncrepl_message_to_entry(
1017         syncinfo_t      *si,
1018         Operation       *op,
1019         LDAPMessage     *msg,
1020         Modifications   **modlist,
1021         Entry                   **entry,
1022         int             syncstate
1023 )
1024 {
1025         Entry           *e = NULL;
1026         BerElement      *ber = NULL;
1027         Modifications   tmp;
1028         Modifications   *mod;
1029         Modifications   **modtail = modlist;
1030
1031         const char      *text;
1032         char txtbuf[SLAP_TEXT_BUFLEN];
1033         size_t textlen = sizeof txtbuf;
1034
1035         struct berval   bdn = {0, NULL}, dn, ndn;
1036         int             rc;
1037
1038         *modlist = NULL;
1039
1040         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1041                 Debug( LDAP_DEBUG_ANY,
1042                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1043                 return -1;
1044         }
1045
1046         op->o_tag = LDAP_REQ_ADD;
1047
1048         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1049
1050         if ( rc != LDAP_SUCCESS ) {
1051                 Debug( LDAP_DEBUG_ANY,
1052                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1053                 return rc;
1054         }
1055
1056         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1057         ber_dupbv( &op->o_req_dn, &dn );
1058         ber_dupbv( &op->o_req_ndn, &ndn );
1059         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1060         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1061
1062         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1063                 if ( entry )
1064                         *entry = NULL;
1065                 return LDAP_SUCCESS;
1066         }
1067
1068         if ( entry == NULL ) {
1069                 return -1;
1070         }
1071
1072         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1073         *entry = e;
1074         e->e_name = op->o_req_dn;
1075         e->e_nname = op->o_req_ndn;
1076
1077         while ( ber_remaining( ber ) ) {
1078                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1079                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1080                 {
1081                         break;
1082                 }
1083
1084                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1085
1086                 mod->sml_op = LDAP_MOD_REPLACE;
1087                 mod->sml_next = NULL;
1088                 mod->sml_desc = NULL;
1089                 mod->sml_type = tmp.sml_type;
1090                 mod->sml_values = tmp.sml_values;
1091                 mod->sml_nvalues = NULL;
1092
1093                 *modtail = mod;
1094                 modtail = &mod->sml_next;
1095         }
1096
1097         if ( *modlist == NULL ) {
1098                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1099                         0, 0, 0 );
1100                 rc = -1;
1101                 goto done;
1102         }
1103
1104         rc = slap_mods_check( *modlist, &text, txtbuf, textlen, NULL );
1105
1106         if ( rc != LDAP_SUCCESS ) {
1107                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1108                         text, 0, 0 );
1109                 goto done;
1110         }
1111
1112         /* Strip out dynamically generated attrs */
1113         for ( modtail = modlist; *modtail ; ) {
1114                 mod = *modtail;
1115                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1116                         *modtail = mod->sml_next;
1117                         slap_mod_free( &mod->sml_mod, 0 );
1118                         ch_free( mod );
1119                 } else {
1120                         modtail = &mod->sml_next;
1121                 }
1122         }
1123
1124         /* Strip out attrs in exattrs list */
1125         for ( modtail = modlist; *modtail ; ) {
1126                 mod = *modtail;
1127                 if ( ldap_charray_inlist( si->si_exattrs,
1128                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1129                         *modtail = mod->sml_next;
1130                         slap_mod_free( &mod->sml_mod, 0 );
1131                         ch_free( mod );
1132                 } else {
1133                         modtail = &mod->sml_next;
1134                 }
1135         }
1136         
1137         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1138         if( rc != LDAP_SUCCESS ) {
1139                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1140                         text, 0, 0 );
1141         }
1142
1143 done:
1144         ber_free ( ber, 0 );
1145         if ( rc != LDAP_SUCCESS ) {
1146                 if ( e ) {
1147                         entry_free( e );
1148                         *entry = e = NULL;
1149                 }
1150         }
1151
1152         return rc;
1153 }
1154
1155 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1156
1157 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1158  * entry if a previous refresh was interrupted before sending us a new
1159  * context state. We try to compare the new entry to the existing entry
1160  * and ignore the new entry if they are the same.
1161  *
1162  * Also, we may get an update where the entryDN has changed, due to
1163  * a ModDn on the provider. We detect this as well, so we can issue
1164  * the corresponding operation locally.
1165  *
1166  * In the case of a modify, we get a list of all the attributes
1167  * in the original entry. Rather than deleting the entry and re-adding it,
1168  * we issue a Modify request that deletes all the attributes and adds all
1169  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1170  * entry.
1171  *
1172  * We don't try to otherwise distinguish ModDN from Modify; in the case of
1173  * a ModDN we will issue both operations on the local database.
1174  */
1175 typedef struct dninfo {
1176         Entry *new_entry;
1177         struct berval dn;
1178         struct berval ndn;
1179         int renamed;    /* Was an existing entry renamed? */
1180         int wasChanged; /* are the attributes changed? */
1181         int attrs;              /* how many attribute types are in the ads list */
1182         AttributeDescription **ads;
1183 } dninfo;
1184
1185 int
1186 syncrepl_entry(
1187         syncinfo_t* si,
1188         Operation *op,
1189         Entry* entry,
1190         Modifications** modlist,
1191         int syncstate,
1192         struct berval* syncUUID,
1193         struct sync_cookie* syncCookie_req,
1194         struct berval* syncCSN )
1195 {
1196         Backend *be = op->o_bd;
1197         slap_callback   cb = { NULL };
1198         struct berval   *syncuuid_bv = NULL;
1199         struct berval   syncUUID_strrep = BER_BVNULL;
1200         struct berval   uuid_bv = BER_BVNULL;
1201
1202         SlapReply       rs_search = {REP_RESULT};
1203         SlapReply       rs_delete = {REP_RESULT};
1204         SlapReply       rs_add = {REP_RESULT};
1205         SlapReply       rs_modify = {REP_RESULT};
1206         Filter f = {0};
1207         AttributeAssertion ava = {0};
1208         int rc = LDAP_SUCCESS;
1209         int ret = LDAP_SUCCESS;
1210
1211         struct berval pdn = BER_BVNULL;
1212         struct berval org_req_dn = BER_BVNULL;
1213         struct berval org_req_ndn = BER_BVNULL;
1214         int     org_managedsait;
1215         dninfo dni = {0};
1216         int     retry = 1;
1217
1218         switch( syncstate ) {
1219         case LDAP_SYNC_PRESENT:
1220                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1221                                         "syncrepl_entry",
1222                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1223                 break;
1224         case LDAP_SYNC_ADD:
1225                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1226                                         "syncrepl_entry",
1227                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1228                 break;
1229         case LDAP_SYNC_DELETE:
1230                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1231                                         "syncrepl_entry",
1232                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1233                 break;
1234         case LDAP_SYNC_MODIFY:
1235                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1236                                         "syncrepl_entry",
1237                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1238                 break;
1239         default:
1240                 Debug( LDAP_DEBUG_ANY, "%s: %s\n",
1241                                         "syncrepl_entry",
1242                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1243         }
1244
1245         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1246                 if ( !si->si_refreshPresent ) {
1247                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1248                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1249                                 syncuuid_cmp, avl_dup_error );
1250                 }
1251         }
1252
1253         if ( syncstate == LDAP_SYNC_PRESENT ) {
1254                 return 0;
1255         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1256                 if ( entry == NULL ) {
1257                         return 0;
1258                 }
1259         }
1260
1261         f.f_choice = LDAP_FILTER_EQUALITY;
1262         f.f_ava = &ava;
1263         ava.aa_desc = slap_schema.si_ad_entryUUID;
1264         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1265         ava.aa_value = *syncUUID;
1266         op->ors_filter = &f;
1267
1268         op->ors_filterstr.bv_len = STRLENOF( "entryUUID=" ) + syncUUID->bv_len;
1269         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1270                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1271         AC_MEMCPY( op->ors_filterstr.bv_val, "entryUUID=", STRLENOF( "entryUUID=" ) );
1272         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "entryUUID=" )],
1273                 syncUUID->bv_val, syncUUID->bv_len );
1274         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1275
1276         op->o_tag = LDAP_REQ_SEARCH;
1277         op->ors_scope = LDAP_SCOPE_SUBTREE;
1278
1279         /* get the entry for this UUID */
1280         op->o_req_dn = si->si_base;
1281         op->o_req_ndn = si->si_base;
1282
1283         op->o_time = slap_get_time();
1284         op->ors_tlimit = SLAP_NO_LIMIT;
1285         op->ors_slimit = 1;
1286
1287         op->ors_attrs = slap_anlist_all_attributes;
1288         op->ors_attrsonly = 0;
1289
1290         /* set callback function */
1291         op->o_callback = &cb;
1292         cb.sc_response = dn_callback;
1293         cb.sc_private = &dni;
1294         dni.new_entry = entry;
1295
1296         if ( limits_check( op, &rs_search ) == 0 ) {
1297                 rc = be->be_search( op, &rs_search );
1298                 Debug( LDAP_DEBUG_SYNC,
1299                                 "syncrepl_entry: %s (%d)\n", 
1300                                 "be_search", rc, 0 );
1301         }
1302
1303         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1304                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1305         }
1306
1307         cb.sc_response = null_callback;
1308         cb.sc_private = si;
1309
1310         if ( entry && entry->e_name.bv_val ) {
1311                 Debug( LDAP_DEBUG_SYNC,
1312                                 "syncrepl_entry: %s\n",
1313                                 entry->e_name.bv_val, 0, 0 );
1314         } else {
1315                 Debug( LDAP_DEBUG_SYNC,
1316                                 "syncrepl_entry: %s\n",
1317                                 dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0, 0 );
1318         }
1319
1320         org_req_dn = op->o_req_dn;
1321         org_req_ndn = op->o_req_ndn;
1322         org_managedsait = get_manageDSAit( op );
1323         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1324
1325         if ( syncstate != LDAP_SYNC_DELETE ) {
1326                 attr_delete( &entry->e_attrs, slap_schema.si_ad_entryUUID );
1327                 attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1328                         &syncUUID_strrep, syncUUID );
1329         }
1330
1331         switch ( syncstate ) {
1332         case LDAP_SYNC_ADD:
1333         case LDAP_SYNC_MODIFY:
1334 retry_add:;
1335                 if ( BER_BVISNULL( &dni.dn )) {
1336
1337                         op->o_req_dn = entry->e_name;
1338                         op->o_req_ndn = entry->e_nname;
1339                         op->o_tag = LDAP_REQ_ADD;
1340                         op->ora_e = entry;
1341
1342                         rc = be->be_add( op, &rs_add );
1343                         Debug( LDAP_DEBUG_SYNC,
1344                                         "syncrepl_entry: %s (%d)\n", 
1345                                         "be_add", rc, 0 );
1346                         switch ( rs_add.sr_err ) {
1347                         case LDAP_SUCCESS:
1348                                 be_entry_release_w( op, entry );
1349                                 ret = 0;
1350                                 break;
1351
1352                         case LDAP_REFERRAL:
1353                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1354                          * only if the suffix entry is not present */
1355                         case LDAP_NO_SUCH_OBJECT:
1356                                 syncrepl_add_glue( op, entry );
1357                                 ret = 0;
1358                                 break;
1359
1360                         /* if an entry was added via syncrepl_add_glue(),
1361                          * it likely has no entryUUID, so the previous
1362                          * be_search() doesn't find it.  In this case,
1363                          * give syncrepl a chance to modify it. Also
1364                          * allow for entries that were recreated with the
1365                          * same DN but a different entryUUID.
1366                          */
1367                         case LDAP_ALREADY_EXISTS:
1368                                 if ( retry ) {
1369                                         Operation       op2 = *op;
1370                                         SlapReply       rs2 = { 0 };
1371                                         slap_callback   cb2 = { 0 };
1372
1373                                         op2.o_tag = LDAP_REQ_SEARCH;
1374                                         op2.o_req_dn = entry->e_name;
1375                                         op2.o_req_ndn = entry->e_nname;
1376                                         op2.ors_scope = LDAP_SCOPE_BASE;
1377                                         op2.ors_attrs = slap_anlist_all_attributes;
1378                                         op2.ors_attrsonly = 0;
1379                                         op2.ors_limit = NULL;
1380                                         op2.ors_slimit = 1;
1381                                         op2.ors_tlimit = SLAP_NO_LIMIT;
1382
1383                                         f.f_choice = LDAP_FILTER_PRESENT;
1384                                         f.f_desc = slap_schema.si_ad_objectClass;
1385                                         op2.ors_filter = &f;
1386                                         op2.ors_filterstr = generic_filterstr;
1387
1388                                         op2.o_callback = &cb2;
1389                                         cb2.sc_response = dn_callback;
1390                                         cb2.sc_private = &dni;
1391
1392                                         be->be_search( &op2, &rs2 );
1393
1394                                         retry = 0;
1395                                         goto retry_add;
1396                                 }
1397                                 /* FALLTHRU */
1398
1399                         default:
1400                                 Debug( LDAP_DEBUG_ANY,
1401                                         "syncrepl_entry : be_add failed (%d)\n",
1402                                         rs_add.sr_err, 0, 0 );
1403                                 ret = 1;
1404                                 break;
1405                         }
1406                         goto done;
1407                 }
1408                 /* FALLTHRU */
1409                 op->o_req_dn = dni.dn;
1410                 op->o_req_ndn = dni.ndn;
1411                 if ( dni.renamed ) {
1412                         struct berval noldp, newp, nnewp;
1413
1414                         op->o_tag = LDAP_REQ_MODRDN;
1415                         dnRdn( &entry->e_name, &op->orr_newrdn );
1416                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
1417
1418                         dnParent( &dni.ndn, &noldp );
1419                         dnParent( &entry->e_nname, &nnewp );
1420                         if ( !dn_match( &noldp, &newp )) {
1421                                 dnParent( &entry->e_name, &newp );
1422                                 op->orr_newSup = &newp;
1423                                 op->orr_nnewSup = &nnewp;
1424                         }
1425                         op->orr_deleteoldrdn = 0;
1426                         rc = be->be_modrdn( op, &rs_modify );
1427                         Debug( LDAP_DEBUG_SYNC,
1428                                         "syncrepl_entry: %s (%d)\n", 
1429                                         "be_modrdn", rc, 0 );
1430                         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
1431                                 op->o_req_dn = entry->e_name;
1432                                 op->o_req_ndn = entry->e_nname;
1433                         } else {
1434                                 ret = 1;
1435                                 goto done;
1436                         }
1437                 }
1438                 if ( dni.wasChanged ) {
1439                         Modifications *mod, *modhead = NULL;
1440                         Modifications *modtail = NULL;
1441                         int i;
1442
1443                         op->o_tag = LDAP_REQ_MODIFY;
1444
1445                         assert( *modlist );
1446
1447                         /* Delete all the old attrs */
1448                         for ( i = 0; i < dni.attrs; i++ ) {
1449                                 mod = ch_malloc( sizeof( Modifications ) );
1450                                 mod->sml_op = LDAP_MOD_DELETE;
1451                                 mod->sml_desc = dni.ads[i];
1452                                 mod->sml_type = mod->sml_desc->ad_cname;
1453                                 mod->sml_values = NULL;
1454                                 mod->sml_nvalues = NULL;
1455                                 if ( !modhead ) modhead = mod;
1456                                 if ( modtail ) {
1457                                         modtail->sml_next = mod;
1458                                 }
1459                                 modtail = mod;
1460                         }
1461
1462                         /* Append passed in list to ours */
1463                         if ( modtail ) {
1464                                 modtail->sml_next = *modlist;
1465                                 *modlist = modhead;
1466                         } else {
1467                                 mod = *modlist;
1468                         }
1469
1470                         /* Find end of this list */
1471                         for ( ; mod != NULL; mod = mod->sml_next ) {
1472                                 modtail = mod;
1473                         }
1474
1475                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1476                         mod->sml_op = LDAP_MOD_REPLACE;
1477                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1478                         mod->sml_type = mod->sml_desc->ad_cname;
1479                         ber_dupbv( &uuid_bv, &syncUUID_strrep );
1480                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1481                         ber_dupbv( &uuid_bv, syncUUID );
1482                         ber_bvarray_add( &mod->sml_nvalues, &uuid_bv );
1483                         modtail->sml_next = mod;
1484                                         
1485                         op->o_tag = LDAP_REQ_MODIFY;
1486                         op->orm_modlist = *modlist;
1487
1488                         rc = be->be_modify( op, &rs_modify );
1489                         Debug( LDAP_DEBUG_SYNC,
1490                                         "syncrepl_entry: %s (%d)\n", 
1491                                         "be_modify", rc, 0 );
1492                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1493                                 Debug( LDAP_DEBUG_ANY,
1494                                         "syncrepl_entry : be_modify failed (%d)\n",
1495                                         rs_modify.sr_err, 0, 0 );
1496                         }
1497                 }
1498                 ret = 1;
1499                 goto done;
1500         case LDAP_SYNC_DELETE :
1501                 if ( !BER_BVISNULL( &dni.dn )) {
1502                         op->o_req_dn = dni.dn;
1503                         op->o_req_ndn = dni.ndn;
1504                         op->o_tag = LDAP_REQ_DELETE;
1505                         rc = be->be_delete( op, &rs_delete );
1506                         Debug( LDAP_DEBUG_SYNC,
1507                                         "syncrepl_entry: %s (%d)\n", 
1508                                         "be_delete", rc, 0 );
1509
1510                         while ( rs_delete.sr_err == LDAP_SUCCESS
1511                                 && op->o_delete_glue_parent ) {
1512                                 op->o_delete_glue_parent = 0;
1513                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1514                                         slap_callback cb = { NULL };
1515                                         cb.sc_response = slap_null_cb;
1516                                         dnParent( &op->o_req_ndn, &pdn );
1517                                         op->o_req_dn = pdn;
1518                                         op->o_req_ndn = pdn;
1519                                         op->o_callback = &cb;
1520                                         op->o_bd->be_delete( op, &rs_delete );
1521                                 } else {
1522                                         break;
1523                                 }
1524                         }
1525                 }
1526                 ret = 0;
1527                 goto done;
1528
1529         default :
1530                 Debug( LDAP_DEBUG_ANY,
1531                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1532                 ret = 1;
1533                 goto done;
1534         }
1535
1536 done :
1537         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
1538                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1539                 BER_BVZERO( &syncUUID_strrep );
1540         }
1541         if ( dni.ads ) {
1542                 op->o_tmpfree( dni.ads, op->o_tmpmemctx );
1543         }
1544         if ( !BER_BVISNULL( &dni.ndn ) ) {
1545                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
1546         }
1547         if ( !BER_BVISNULL( &dni.dn ) ) {
1548                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
1549         }
1550         return ret;
1551 }
1552
1553 static struct berval gcbva[] = {
1554         BER_BVC("top"),
1555         BER_BVC("glue"),
1556         BER_BVNULL
1557 };
1558
1559 #define NP_DELETE_ONE   2
1560
1561 static void
1562 syncrepl_del_nonpresent(
1563         Operation *op,
1564         syncinfo_t *si,
1565         BerVarray uuids )
1566 {
1567         Backend* be = op->o_bd;
1568         slap_callback   cb = { NULL };
1569         SlapReply       rs_search = {REP_RESULT};
1570         SlapReply       rs_delete = {REP_RESULT};
1571         SlapReply       rs_modify = {REP_RESULT};
1572         struct nonpresent_entry *np_list, *np_prev;
1573         int rc;
1574         Modifications *ml;
1575         Modifications *mlnext;
1576         Modifications *mod;
1577         Modifications *modlist = NULL;
1578         Modifications **modtail;
1579         AttributeName   an[2];
1580
1581         struct berval pdn = BER_BVNULL;
1582         struct berval org_req_dn = BER_BVNULL;
1583         struct berval org_req_ndn = BER_BVNULL;
1584         int     org_managedsait;
1585
1586         op->o_req_dn = si->si_base;
1587         op->o_req_ndn = si->si_base;
1588
1589         cb.sc_response = nonpresent_callback;
1590         cb.sc_private = si;
1591
1592         op->o_callback = &cb;
1593         op->o_tag = LDAP_REQ_SEARCH;
1594         op->ors_scope = si->si_scope;
1595         op->ors_deref = LDAP_DEREF_NEVER;
1596         op->o_time = slap_get_time();
1597         op->ors_tlimit = SLAP_NO_LIMIT;
1598
1599
1600         if ( uuids ) {
1601                 Filter uf;
1602                 AttributeAssertion eq;
1603                 int i;
1604
1605                 op->ors_attrsonly = 1;
1606                 op->ors_attrs = slap_anlist_no_attrs;
1607                 op->ors_limit = NULL;
1608                 op->ors_filter = &uf;
1609                 op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1610
1611                 uf.f_ava = &eq;
1612                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
1613                 uf.f_next = NULL;
1614                 uf.f_choice = LDAP_FILTER_EQUALITY;
1615                 si->si_refreshDelete |= NP_DELETE_ONE;
1616
1617                 for (i=0; uuids[i].bv_val; i++) {
1618                         op->ors_slimit = 1;
1619                         uf.f_av_value = uuids[i];
1620                         rc = be->be_search( op, &rs_search );
1621                 }
1622                 si->si_refreshDelete ^= NP_DELETE_ONE;
1623         } else {
1624                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
1625                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1626                 an[0].an_desc = slap_schema.si_ad_entryUUID;
1627                 op->ors_attrs = an;
1628                 op->ors_slimit = SLAP_NO_LIMIT;
1629                 op->ors_attrsonly = 0;
1630                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
1631                 op->ors_filterstr = si->si_filterstr;
1632                 op->o_nocaching = 1;
1633                 op->o_managedsait = SLAP_CONTROL_NONE;
1634
1635                 if ( limits_check( op, &rs_search ) == 0 ) {
1636                         rc = be->be_search( op, &rs_search );
1637                 }
1638                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
1639         }
1640
1641         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1642         op->o_nocaching = 0;
1643
1644         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
1645                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
1646                 while ( np_list != NULL ) {
1647                         LDAP_LIST_REMOVE( np_list, npe_link );
1648                         np_prev = np_list;
1649                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
1650                         op->o_tag = LDAP_REQ_DELETE;
1651                         op->o_callback = &cb;
1652                         cb.sc_response = null_callback;
1653                         cb.sc_private = si;
1654                         op->o_req_dn = *np_prev->npe_name;
1655                         op->o_req_ndn = *np_prev->npe_nname;
1656                         rc = op->o_bd->be_delete( op, &rs_delete );
1657
1658                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
1659                                 modtail = &modlist;
1660                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1661                                 mod->sml_op = LDAP_MOD_REPLACE;
1662                                 mod->sml_desc = slap_schema.si_ad_objectClass;
1663                                 mod->sml_type = mod->sml_desc->ad_cname;
1664                                 mod->sml_values = &gcbva[0];
1665                                 *modtail = mod;
1666                                 modtail = &mod->sml_next;
1667
1668                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1669                                 mod->sml_op = LDAP_MOD_REPLACE;
1670                                 mod->sml_desc = slap_schema.si_ad_structuralObjectClass;
1671                                 mod->sml_type = mod->sml_desc->ad_cname;
1672                                 mod->sml_values = &gcbva[1];
1673                                 *modtail = mod;
1674                                 modtail = &mod->sml_next;
1675
1676                                 op->o_tag = LDAP_REQ_MODIFY;
1677                                 op->orm_modlist = modlist;
1678
1679                                 rc = be->be_modify( op, &rs_modify );
1680
1681                                 for ( ml = modlist; ml != NULL; ml = mlnext ) {
1682                                         mlnext = ml->sml_next;
1683                                         free( ml );
1684                                 }
1685                         }
1686
1687                         org_managedsait = get_manageDSAit( op );
1688                         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1689
1690                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
1691                                         op->o_delete_glue_parent ) {
1692                                 op->o_delete_glue_parent = 0;
1693                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1694                                         slap_callback cb = { NULL };
1695                                         cb.sc_response = slap_null_cb;
1696                                         dnParent( &op->o_req_ndn, &pdn );
1697                                         op->o_req_dn = pdn;
1698                                         op->o_req_ndn = pdn;
1699                                         op->o_callback = &cb;
1700                                         /* give it a root privil ? */
1701                                         op->o_bd->be_delete( op, &rs_delete );
1702                                 } else {
1703                                         break;
1704                             }
1705                         }
1706
1707                         op->o_managedsait = org_managedsait;
1708                         op->o_req_dn = org_req_dn;
1709                         op->o_req_ndn = org_req_ndn;
1710                         op->o_delete_glue_parent = 0;
1711
1712                         ber_bvfree( np_prev->npe_name );
1713                         ber_bvfree( np_prev->npe_nname );
1714                         BER_BVZERO( &op->o_req_dn );
1715                         BER_BVZERO( &op->o_req_ndn );
1716                         ch_free( np_prev );
1717                 }
1718         }
1719
1720         return;
1721 }
1722
1723 void
1724 syncrepl_add_glue(
1725         Operation* op,
1726         Entry *e )
1727 {
1728         Backend *be = op->o_bd;
1729         slap_callback cb = { NULL };
1730         Attribute       *a;
1731         int     rc;
1732         int suffrdns;
1733         int i;
1734         struct berval dn = {0, NULL};
1735         struct berval ndn = {0, NULL};
1736         Entry   *glue;
1737         SlapReply       rs_add = {REP_RESULT};
1738         char    *ptr, *comma;
1739
1740         op->o_tag = LDAP_REQ_ADD;
1741         op->o_callback = &cb;
1742         cb.sc_response = null_callback;
1743         cb.sc_private = NULL;
1744
1745         dn = e->e_name;
1746         ndn = e->e_nname;
1747
1748         /* count RDNs in suffix */
1749         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
1750                 for ( i = 0, ptr = be->be_nsuffix[0].bv_val; ptr; ptr = strchr( ptr, ',' ) ) {
1751                         ptr++;
1752                         i++;
1753                 }
1754                 suffrdns = i;
1755         } else {
1756                 /* suffix is "" */
1757                 suffrdns = 0;
1758         }
1759
1760         /* Start with BE suffix */
1761         for ( i = 0, ptr = NULL; i < suffrdns; i++ ) {
1762                 comma = strrchr( dn.bv_val, ',' );
1763                 if ( ptr ) *ptr = ',';
1764                 if ( comma ) *comma = '\0';
1765                 ptr = comma;
1766         }
1767         if ( ptr ) {
1768                 *ptr++ = ',';
1769                 dn.bv_len -= ptr - dn.bv_val;
1770                 dn.bv_val = ptr;
1771         }
1772         /* the normalizedDNs are always the same length, no counting
1773          * required.
1774          */
1775         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
1776                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
1777                 ndn.bv_len = be->be_nsuffix[0].bv_len;
1778         }
1779
1780         while ( ndn.bv_val > e->e_nname.bv_val ) {
1781                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
1782                 ber_dupbv( &glue->e_name, &dn );
1783                 ber_dupbv( &glue->e_nname, &ndn );
1784
1785                 a = ch_calloc( 1, sizeof( Attribute ));
1786                 a->a_desc = slap_schema.si_ad_objectClass;
1787
1788                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1789                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
1790                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
1791                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
1792
1793                 a->a_nvals = a->a_vals;
1794
1795                 a->a_next = glue->e_attrs;
1796                 glue->e_attrs = a;
1797
1798                 a = ch_calloc( 1, sizeof( Attribute ));
1799                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1800
1801                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1802                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
1803                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
1804
1805                 a->a_nvals = a->a_vals;
1806
1807                 a->a_next = glue->e_attrs;
1808                 glue->e_attrs = a;
1809
1810                 op->o_req_dn = glue->e_name;
1811                 op->o_req_ndn = glue->e_nname;
1812                 op->ora_e = glue;
1813                 rc = be->be_add ( op, &rs_add );
1814                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
1815                         be_entry_release_w( op, glue );
1816                 } else {
1817                 /* incl. ALREADY EXIST */
1818                         entry_free( glue );
1819                 }
1820
1821                 /* Move to next child */
1822                 for (ptr = dn.bv_val-2; ptr > e->e_name.bv_val && *ptr != ','; ptr--) {
1823                         /* empty */
1824                 }
1825                 if ( ptr == e->e_name.bv_val ) break;
1826                 dn.bv_val = ++ptr;
1827                 dn.bv_len = e->e_name.bv_len - (ptr-e->e_name.bv_val);
1828                 for( ptr = ndn.bv_val-2;
1829                         ptr > e->e_nname.bv_val && *ptr != ',';
1830                         ptr--)
1831                 {
1832                         /* empty */
1833                 }
1834                 ndn.bv_val = ++ptr;
1835                 ndn.bv_len = e->e_nname.bv_len - (ptr-e->e_nname.bv_val);
1836         }
1837
1838         op->o_req_dn = e->e_name;
1839         op->o_req_ndn = e->e_nname;
1840         op->ora_e = e;
1841         rc = be->be_add ( op, &rs_add );
1842         if ( rs_add.sr_err == LDAP_SUCCESS ) {
1843                 be_entry_release_w( op, e );
1844         } else {
1845                 entry_free( e );
1846         }
1847
1848         return;
1849 }
1850
1851 static struct berval ocbva[] = {
1852         BER_BVC("top"),
1853         BER_BVC("subentry"),
1854         BER_BVC("syncConsumerSubentry"),
1855         BER_BVNULL
1856 };
1857
1858 static struct berval cnbva[] = {
1859         BER_BVNULL,
1860         BER_BVNULL
1861 };
1862
1863 static struct berval ssbva[] = {
1864         BER_BVC("{}"),
1865         BER_BVNULL
1866 };
1867
1868 static struct berval scbva[] = {
1869         BER_BVNULL,
1870         BER_BVNULL
1871 };
1872
1873 void
1874 syncrepl_updateCookie(
1875         syncinfo_t *si,
1876         Operation *op,
1877         struct berval *pdn,
1878         struct sync_cookie *syncCookie )
1879 {
1880         Backend *be = op->o_bd;
1881         Modifications *ml;
1882         Modifications *mlnext;
1883         Modifications *mod;
1884         Modifications *modlist = NULL;
1885         Modifications **modtail = &modlist;
1886
1887         const char      *text;
1888         char txtbuf[SLAP_TEXT_BUFLEN];
1889         size_t textlen = sizeof txtbuf;
1890
1891         Entry* e = NULL;
1892         int rc;
1893
1894         char syncrepl_cbuf[sizeof(CN_STR SYNCREPL_STR)];
1895         struct berval slap_syncrepl_dn_bv = BER_BVNULL;
1896         struct berval slap_syncrepl_cn_bv = BER_BVNULL;
1897         
1898         slap_callback cb = { NULL };
1899         SlapReply       rs_add = {REP_RESULT};
1900         SlapReply       rs_modify = {REP_RESULT};
1901
1902         slap_sync_cookie_free( &si->si_syncCookie, 0 );
1903         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
1904
1905         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1906         mod->sml_op = LDAP_MOD_REPLACE;
1907         mod->sml_desc = slap_schema.si_ad_objectClass;
1908         mod->sml_type = mod->sml_desc->ad_cname;
1909         mod->sml_values = ocbva;
1910         *modtail = mod;
1911         modtail = &mod->sml_next;
1912
1913         ber_dupbv( &cnbva[0], (struct berval *) &slap_syncrepl_bvc );
1914         assert( si->si_rid < 1000 );
1915         cnbva[0].bv_len = snprintf( cnbva[0].bv_val,
1916                 slap_syncrepl_bvc.bv_len + 1,
1917                 "syncrepl%ld", si->si_rid );
1918         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1919         mod->sml_op = LDAP_MOD_REPLACE;
1920         mod->sml_desc = slap_schema.si_ad_cn;
1921         mod->sml_type = mod->sml_desc->ad_cname;
1922         mod->sml_values = cnbva;
1923         *modtail = mod;
1924         modtail = &mod->sml_next;
1925
1926         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1927         mod->sml_op = LDAP_MOD_REPLACE;
1928         mod->sml_desc = slap_schema.si_ad_subtreeSpecification;
1929         mod->sml_type = mod->sml_desc->ad_cname;
1930         mod->sml_values = ssbva;
1931         *modtail = mod;
1932         modtail = &mod->sml_next;
1933
1934         /* Keep this last, so we can avoid touching the previous
1935          * attributes unnecessarily.
1936          */
1937         if ( scbva[0].bv_val ) ch_free( scbva[0].bv_val );
1938         ber_dupbv( &scbva[0], &si->si_syncCookie.octet_str[0] );
1939         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1940         mod->sml_op = LDAP_MOD_REPLACE;
1941         mod->sml_desc = slap_schema.si_ad_syncreplCookie;
1942         mod->sml_type = mod->sml_desc->ad_cname;
1943         mod->sml_values = scbva;
1944         *modtail = mod;
1945         modtail = &mod->sml_next;
1946
1947         slap_queue_csn( op, si->si_syncCookie.ctxcsn );
1948
1949         mlnext = mod;
1950
1951         op->o_tag = LDAP_REQ_ADD;
1952         rc = slap_mods_opattrs( op, modlist, modtail,
1953                  &text, txtbuf, textlen, 0 );
1954
1955         for ( ml = modlist; ml != NULL; ml = ml->sml_next ) {
1956                 ml->sml_op = LDAP_MOD_REPLACE;
1957         }
1958
1959         if( rc != LDAP_SUCCESS ) {
1960                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods opattrs (%s)\n",
1961                          text, 0, 0 );
1962         }
1963
1964         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1965
1966         slap_syncrepl_cn_bv.bv_val = syncrepl_cbuf;
1967         assert( si->si_rid < 1000 );
1968         slap_syncrepl_cn_bv.bv_len = snprintf( slap_syncrepl_cn_bv.bv_val,
1969                 slap_syncrepl_cn_bvc.bv_len + 1,
1970                 "cn=syncrepl%ld", si->si_rid );
1971
1972         build_new_dn( &slap_syncrepl_dn_bv, pdn, &slap_syncrepl_cn_bv,
1973                 op->o_tmpmemctx );
1974         ber_dupbv( &e->e_name, &slap_syncrepl_dn_bv );
1975         ber_dupbv( &e->e_nname, &slap_syncrepl_dn_bv );
1976
1977         if ( !BER_BVISNULL( &slap_syncrepl_dn_bv ) ) {
1978                 slap_sl_free( slap_syncrepl_dn_bv.bv_val, op->o_tmpmemctx );
1979         }
1980
1981         e->e_attrs = NULL;
1982
1983         rc = slap_mods2entry( modlist, &e, 1, 1, &text, txtbuf, textlen );
1984
1985         if( rc != LDAP_SUCCESS ) {
1986                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods2entry (%s)\n",
1987                          text, 0, 0 );
1988         }
1989
1990         cb.sc_response = null_callback;
1991         cb.sc_private = si;
1992
1993         op->o_callback = &cb;
1994         op->o_req_dn = e->e_name;
1995         op->o_req_ndn = e->e_nname;
1996
1997         /* update persistent cookie */
1998 update_cookie_retry:
1999         op->o_tag = LDAP_REQ_MODIFY;
2000         /* Just modify the cookie value, not the entire entry */
2001         op->orm_modlist = mod;
2002         rc = be->be_modify( op, &rs_modify );
2003
2004         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2005                 if ( rs_modify.sr_err == LDAP_REFERRAL ||
2006                          rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
2007                         op->o_tag = LDAP_REQ_ADD;
2008                         op->ora_e = e;
2009                         rc = be->be_add( op, &rs_add );
2010                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
2011                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS ) {
2012                                         goto update_cookie_retry;
2013                                 } else if ( rs_add.sr_err == LDAP_REFERRAL ||
2014                                                         rs_add.sr_err == LDAP_NO_SUCH_OBJECT ) {
2015                                         Debug( LDAP_DEBUG_ANY,
2016                                                 "cookie will be non-persistent\n",
2017                                                 0, 0, 0 );
2018                                 } else {
2019                                         Debug( LDAP_DEBUG_ANY,
2020                                                 "be_add failed (%d)\n", rs_add.sr_err, 0, 0 );
2021                                 }
2022                         } else {
2023                                 be_entry_release_w( op, e );
2024                                 goto done;
2025                         }
2026                 } else {
2027                         Debug( LDAP_DEBUG_ANY,
2028                                 "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
2029                 }
2030         }
2031         if ( e != NULL ) {
2032                 entry_free( e );
2033         }
2034
2035 done :
2036         slap_graduate_commit_csn( op );
2037
2038
2039         if ( !BER_BVISNULL( &cnbva[0] ) ) {
2040                 ch_free( cnbva[0].bv_val );
2041                 BER_BVZERO( &cnbva[0] );
2042         }
2043         if ( !BER_BVISNULL( &scbva[0] ) ) {
2044                 ch_free( scbva[0].bv_val );
2045                 BER_BVZERO( &scbva[0] );
2046         }
2047
2048         if ( mlnext->sml_next ) {
2049                 slap_mods_free( mlnext->sml_next );
2050                 mlnext->sml_next = NULL;
2051         }
2052
2053         for (ml = modlist ; ml != NULL; ml = mlnext ) {
2054                 mlnext = ml->sml_next;
2055                 free( ml );
2056         }
2057
2058         return;
2059 }
2060
2061 static int
2062 dn_callback(
2063         Operation*      op,
2064         SlapReply*      rs )
2065 {
2066         dninfo *dni = op->o_callback->sc_private;
2067
2068         if ( rs->sr_type == REP_SEARCH ) {
2069                 if ( !BER_BVISNULL( &dni->dn ) ) {
2070                         Debug( LDAP_DEBUG_ANY,
2071                                 "dn_callback : consistency error - "
2072                                 "entryUUID is not unique\n", 0, 0, 0 );
2073                 } else {
2074                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2075                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2076                         /* If there is a new entry, see if it differs from the old.
2077                          * We compare the non-normalized values so that cosmetic changes
2078                          * in the provider are always propagated.
2079                          */
2080                         if ( dni->new_entry ) {
2081                                 Attribute *old, *new;
2082                                 int i;
2083
2084                                 /* Did the DN change? Note that we don't explicitly try to
2085                                  * discover if the deleteOldRdn argument applies here. It
2086                                  * would save an unnecessary Modify if we detected it, but
2087                                  * that's a fair amount of trouble to compare the two attr
2088                                  * lists in detail.
2089                                  */
2090                                 if ( !dn_match( &rs->sr_entry->e_name,
2091                                                 &dni->new_entry->e_name ) )
2092                                 {
2093                                         dni->renamed = 1;
2094                                 }
2095
2096                                 for ( i = 0, old = rs->sr_entry->e_attrs;
2097                                                 old;
2098                                                 i++, old = old->a_next )
2099                                         ;
2100
2101                                 dni->attrs = i;
2102
2103                                 /* We assume that attributes are saved in the same order
2104                                  * in the remote and local databases. So if we walk through
2105                                  * the attributeDescriptions one by one they should match in
2106                                  * lock step. If not, we signal a change. Otherwise we test
2107                                  * all the values...
2108                                  */
2109                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2110                                                 old && new;
2111                                                 old = old->a_next, new = new->a_next )
2112                                 {
2113                                         if ( old->a_desc != new->a_desc ) {
2114                                                 dni->wasChanged = 1;
2115                                                 break;
2116                                         }
2117                                         for ( i = 0; ; i++ ) {
2118                                                 int nold, nnew;
2119                                                 nold = BER_BVISNULL( &old->a_vals[i] );
2120                                                 nnew = BER_BVISNULL( &new->a_vals[i] );
2121                                                 /* If both are empty, stop looking */
2122                                                 if ( nold && nnew ) {
2123                                                         break;
2124                                                 }
2125                                                 /* If they are different, stop looking */
2126                                                 if ( nold != nnew ) {
2127                                                         dni->wasChanged = 1;
2128                                                         break;
2129                                                 }
2130                                                 if ( ber_bvcmp( &old->a_vals[i], &new->a_vals[i] )) {
2131                                                         dni->wasChanged = 1;
2132                                                         break;
2133                                                 }
2134                                         }
2135                                         if ( dni->wasChanged ) break;
2136                                 }
2137                                 if ( dni->wasChanged ) {
2138                                         dni->ads = op->o_tmpalloc( dni->attrs *
2139                                                 sizeof(AttributeDescription *), op->o_tmpmemctx );
2140                                         i = 0;
2141                                         for ( old = rs->sr_entry->e_attrs; old; old = old->a_next ) {
2142                                                 dni->ads[i] = old->a_desc;
2143                                                 i++;
2144                                         }
2145                                 }
2146                         }
2147                 }
2148         } else if ( rs->sr_type == REP_RESULT ) {
2149                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2150                         Debug( LDAP_DEBUG_ANY,
2151                                 "dn_callback : consistency error - "
2152                                 "entryUUID is not unique\n", 0, 0, 0 );
2153                 }
2154         }
2155
2156         return LDAP_SUCCESS;
2157 }
2158
2159 static int
2160 nonpresent_callback(
2161         Operation*      op,
2162         SlapReply*      rs )
2163 {
2164         syncinfo_t *si = op->o_callback->sc_private;
2165         Attribute *a;
2166         int count = 0;
2167         struct berval* present_uuid = NULL;
2168         struct nonpresent_entry *np_entry;
2169
2170         if ( rs->sr_type == REP_RESULT ) {
2171                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2172                 si->si_presentlist = NULL;
2173
2174         } else if ( rs->sr_type == REP_SEARCH ) {
2175                 if ( !(si->si_refreshDelete & NP_DELETE_ONE )) {
2176                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2177
2178                         if ( a == NULL ) return 0;
2179
2180                         present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2181                                 syncuuid_cmp );
2182                 }
2183
2184                 if ( present_uuid == NULL ) {
2185                         np_entry = (struct nonpresent_entry *)
2186                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2187                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2188                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2189                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2190
2191                 } else {
2192                         avl_delete( &si->si_presentlist,
2193                                         &a->a_nvals[0], syncuuid_cmp );
2194                         ch_free( present_uuid->bv_val );
2195                         ch_free( present_uuid );
2196                 }
2197         }
2198         return LDAP_SUCCESS;
2199 }
2200
2201 static int
2202 null_callback(
2203         Operation*      op,
2204         SlapReply*      rs )
2205 {
2206         if ( rs->sr_err != LDAP_SUCCESS &&
2207                 rs->sr_err != LDAP_REFERRAL &&
2208                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2209                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2210                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2211         {
2212                 Debug( LDAP_DEBUG_ANY,
2213                         "null_callback : error code 0x%x\n",
2214                         rs->sr_err, 0, 0 );
2215         }
2216         return LDAP_SUCCESS;
2217 }
2218
2219 Entry *
2220 slap_create_syncrepl_entry(
2221         Backend *be,
2222         struct berval *context_csn,
2223         struct berval *rdn,
2224         struct berval *cn )
2225 {
2226         Entry* e;
2227
2228         struct berval bv;
2229
2230         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
2231
2232         attr_merge( e, slap_schema.si_ad_objectClass, ocbva, NULL );
2233
2234         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
2235                 &ocbva[1], NULL );
2236
2237         attr_merge_one( e, slap_schema.si_ad_cn, cn, NULL );
2238
2239         if ( context_csn ) {
2240                 attr_merge_one( e, slap_schema.si_ad_syncreplCookie,
2241                         context_csn, NULL );
2242         }
2243
2244         BER_BVSTR( &bv, "{}" );
2245         attr_merge_one( e, slap_schema.si_ad_subtreeSpecification, &bv, NULL );
2246
2247         build_new_dn( &e->e_name, &be->be_nsuffix[0], rdn, NULL );
2248         ber_dupbv( &e->e_nname, &e->e_name );
2249
2250         return e;
2251 }
2252
2253 struct berval *
2254 slap_uuidstr_from_normalized(
2255         struct berval* uuidstr,
2256         struct berval* normalized,
2257         void *ctx )
2258 {
2259         struct berval *new;
2260         unsigned char nibble;
2261         int i, d = 0;
2262
2263         if ( normalized == NULL ) return NULL;
2264         if ( normalized->bv_len != 16 ) return NULL;
2265
2266         if ( uuidstr ) {
2267                 new = uuidstr;
2268         } else {
2269                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2270                 if ( new == NULL ) {
2271                         return NULL;
2272                 }
2273         }
2274
2275         new->bv_len = 36;
2276
2277         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2278                 if ( new != uuidstr ) {
2279                         slap_sl_free( new, ctx );
2280                 }
2281                 return NULL;
2282         }
2283
2284         for ( i = 0; i < 16; i++ ) {
2285                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2286                         new->bv_val[(i<<1)+d] = '-';
2287                         d += 1;
2288                 }
2289
2290                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2291                 if ( nibble < 10 ) {
2292                         new->bv_val[(i<<1)+d] = nibble + '0';
2293                 } else {
2294                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2295                 }
2296
2297                 nibble = (normalized->bv_val[i]) & 0xF;
2298                 if ( nibble < 10 ) {
2299                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2300                 } else {
2301                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2302                 }
2303         }
2304
2305         new->bv_val[new->bv_len] = '\0';
2306         return new;
2307 }
2308
2309 static int
2310 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2311 {
2312         const struct berval *uuid1 = v_uuid1;
2313         const struct berval *uuid2 = v_uuid2;
2314         int rc = uuid1->bv_len - uuid2->bv_len;
2315         if ( rc ) return rc;
2316         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2317 }
2318
2319 static void
2320 avl_ber_bvfree( void *v_bv )
2321 {
2322         struct berval   *bv = (struct berval *)v_bv;
2323         
2324         if( v_bv == NULL ) return;
2325         if ( !BER_BVISNULL( bv ) ) {
2326                 ch_free( bv->bv_val );
2327         }
2328         ch_free( (char *) bv );
2329 }
2330
2331 void
2332 syncinfo_free( syncinfo_t *sie )
2333 {
2334         if ( sie->si_provideruri ) {
2335                 ch_free( sie->si_provideruri );
2336         }
2337         if ( sie->si_provideruri_bv ) {
2338                 ber_bvarray_free( sie->si_provideruri_bv );
2339         }
2340         if ( sie->si_binddn ) {
2341                 ch_free( sie->si_binddn );
2342         }
2343         if ( sie->si_passwd ) {
2344                 ch_free( sie->si_passwd );
2345         }
2346         if ( sie->si_saslmech ) {
2347                 ch_free( sie->si_saslmech );
2348         }
2349         if ( sie->si_secprops ) {
2350                 ch_free( sie->si_secprops );
2351         }
2352         if ( sie->si_realm ) {
2353                 ch_free( sie->si_realm );
2354         }
2355         if ( sie->si_authcId ) {
2356                 ch_free( sie->si_authcId );
2357         }
2358         if ( sie->si_authzId ) {
2359                 ch_free( sie->si_authzId );
2360         }
2361         if ( sie->si_filterstr.bv_val ) {
2362                 ch_free( sie->si_filterstr.bv_val );
2363         }
2364         if ( sie->si_base.bv_val ) {
2365                 ch_free( sie->si_base.bv_val );
2366         }
2367         if ( sie->si_attrs ) {
2368                 int i = 0;
2369                 while ( sie->si_attrs[i] != NULL ) {
2370                         ch_free( sie->si_attrs[i] );
2371                         i++;
2372                 }
2373                 ch_free( sie->si_attrs );
2374         }
2375         if ( sie->si_exattrs ) {
2376                 int i = 0;
2377                 while ( sie->si_exattrs[i] != NULL ) {
2378                         ch_free( sie->si_exattrs[i] );
2379                         i++;
2380                 }
2381                 ch_free( sie->si_exattrs );
2382         }
2383         if ( sie->si_anlist ) {
2384                 int i = 0;
2385                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2386                         ch_free( sie->si_anlist[i].an_name.bv_val );
2387                         i++;
2388                 }
2389                 ch_free( sie->si_anlist );
2390         }
2391         if ( sie->si_exanlist ) {
2392                 int i = 0;
2393                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2394                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2395                         i++;
2396                 }
2397                 ch_free( sie->si_exanlist );
2398         }
2399         if ( sie->si_retryinterval ) {
2400                 ch_free( sie->si_retryinterval );
2401         }
2402         if ( sie->si_retrynum ) {
2403                 ch_free( sie->si_retrynum );
2404         }
2405         if ( sie->si_retrynum_init ) {
2406                 ch_free( sie->si_retrynum_init );
2407         }
2408         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2409         if ( sie->si_presentlist ) {
2410             avl_free( sie->si_presentlist, avl_ber_bvfree );
2411         }
2412         if ( sie->si_ld ) {
2413                 ldap_ld_free( sie->si_ld, 1, NULL, NULL );
2414         }
2415         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2416                 struct nonpresent_entry* npe;
2417                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2418                 LDAP_LIST_REMOVE( npe, npe_link );
2419                 if ( npe->npe_name ) {
2420                         if ( npe->npe_name->bv_val ) {
2421                                 ch_free( npe->npe_name->bv_val );
2422                         }
2423                         ch_free( npe->npe_name );
2424                 }
2425                 if ( npe->npe_nname ) {
2426                         if ( npe->npe_nname->bv_val ) {
2427                                 ch_free( npe->npe_nname->bv_val );
2428                         }
2429                         ch_free( npe->npe_nname );
2430                 }
2431                 ch_free( npe );
2432         }
2433         ch_free( sie );
2434 }