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