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