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