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