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