]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
cb39b532c813baf648c8296793da0d7dcbc082d8
[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         slap_sl_free( op->o_req_ndn.bv_val, op->o_tmpmemctx );
411
412         return rc;
413 }
414
415 static int
416 do_syncrep2(
417         Operation *op,
418         syncinfo_t *si )
419 {
420         LDAPControl     **rctrls = NULL;
421         LDAPControl     *rctrlp;
422
423         BerElementBuffer berbuf;
424         BerElement      *ber = (BerElement *)&berbuf;
425
426         LDAPMessage     *res = NULL;
427         LDAPMessage     *msg = NULL;
428
429         char            *retoid = NULL;
430         struct berval   *retdata = NULL;
431
432         Entry           *entry = NULL;
433
434         int             syncstate;
435         struct berval   syncUUID = BER_BVNULL;
436         struct sync_cookie      syncCookie = { NULL, -1, NULL };
437         struct sync_cookie      syncCookie_req = { NULL, -1, NULL };
438         struct berval           cookie = BER_BVNULL;
439
440         int     rc, err, i;
441         ber_len_t       len;
442
443         int rc_efree = 1;
444
445         struct berval   *psub;
446         Modifications   *modlist = NULL;
447
448         const char              *text;
449         int                             match;
450
451         struct timeval *tout_p = NULL;
452         struct timeval tout = { 0, 0 };
453
454         int             refreshDeletes = 0;
455         int             refreshDone = 1;
456         BerVarray syncUUIDs = NULL;
457         ber_tag_t si_tag;
458
459         if ( slapd_shutdown ) {
460                 rc = -2;
461                 goto done;
462         }
463
464         ber_init2( ber, NULL, LBER_USE_DER );
465         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
466
467         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2\n", 0, 0, 0 );
468
469         psub = &si->si_be->be_nsuffix[0];
470
471         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
472
473         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
474                 tout_p = &tout;
475         } else {
476                 tout_p = NULL;
477         }
478
479         while (( rc = ldap_result( si->si_ld, LDAP_RES_ANY, LDAP_MSG_ONE,
480                 tout_p, &res )) > 0 )
481         {
482                 if ( slapd_shutdown ) {
483                         rc = -2;
484                         goto done;
485                 }
486                 for( msg = ldap_first_message( si->si_ld, res );
487                         msg != NULL;
488                         msg = ldap_next_message( si->si_ld, msg ) )
489                 {
490                         switch( ldap_msgtype( msg ) ) {
491                         case LDAP_RES_SEARCH_ENTRY:
492                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
493                                 /* we can't work without the control */
494                                 if ( !rctrls ) {
495                                         rc = -1;
496                                         goto done;
497                                 }
498                                 rctrlp = *rctrls;
499                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
500                                 ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
501                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
502                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
503                                         if ( cookie.bv_val ) {
504                                                 struct berval tmp_bv;
505                                                 ber_dupbv( &tmp_bv, &cookie );
506                                                 ber_bvarray_add( &syncCookie.octet_str, &tmp_bv );
507                                         }
508                                         if ( syncCookie.octet_str &&
509                                                         syncCookie.octet_str[0].bv_val )
510                                                 slap_parse_sync_cookie( &syncCookie );
511                                 }
512                                 if ( syncrepl_message_to_entry( si, op, msg,
513                                         &modlist, &entry, syncstate ) == LDAP_SUCCESS ) {
514                                         rc_efree = syncrepl_entry( si, op, entry, modlist,
515                                                 syncstate, &syncUUID, &syncCookie_req );
516                                         if ( syncCookie.octet_str &&
517                                                 syncCookie.octet_str[0].bv_val )
518                                         {
519                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
520                                         }
521                                 }
522                                 ldap_controls_free( rctrls );
523                                 if ( modlist ) {
524                                         slap_mods_free( modlist );
525                                 }
526                                 if ( rc_efree && entry ) {
527                                         entry_free( entry );
528                                 }
529                                 entry = NULL;
530                                 break;
531
532                         case LDAP_RES_SEARCH_REFERENCE:
533                                 Debug( LDAP_DEBUG_ANY,
534                                         "do_syncrep2 : reference received\n", 0, 0, 0 );
535                                 break;
536
537                         case LDAP_RES_SEARCH_RESULT:
538                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
539                                         &rctrls, 0 );
540                                 if ( rctrls ) {
541                                         rctrlp = *rctrls;
542                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
543
544                                         ber_scanf( ber, "{" /*"}"*/);
545                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
546                                                 ber_scanf( ber, "m", &cookie );
547                                                 if ( cookie.bv_val ) {
548                                                         struct berval tmp_bv;
549                                                         ber_dupbv( &tmp_bv, &cookie );
550                                                         ber_bvarray_add( &syncCookie.octet_str, &tmp_bv);
551                                                 }
552                                                 if ( syncCookie.octet_str &&
553                                                         syncCookie.octet_str[0].bv_val )
554                                                 {
555                                                         slap_parse_sync_cookie( &syncCookie );
556                                                 }
557                                         }
558                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
559                                         {
560                                                 ber_scanf( ber, "b", &refreshDeletes );
561                                         }
562                                         ber_scanf( ber, /*"{"*/ "}" );
563                                 }
564                                 if ( syncCookie_req.ctxcsn == NULL ) {
565                                         match = -1;
566                                 } else if ( syncCookie.ctxcsn == NULL ) {
567                                         match = 1;
568                                 } else {
569                                         value_match( &match, slap_schema.si_ad_entryCSN,
570                                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
571                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
572                                                 &syncCookie_req.ctxcsn[0], &syncCookie.ctxcsn[0],
573                                                 &text );
574                                 }
575                                 if ( syncCookie.octet_str && syncCookie.octet_str->bv_val &&
576                                         match < 0 && err == LDAP_SUCCESS )
577                                 {
578                                         syncrepl_updateCookie( si, op, psub, &syncCookie );
579                                 }
580                                 if ( rctrls ) {
581                                         ldap_controls_free( rctrls );
582                                 }
583                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
584                                         /* FIXME : different error behaviors according to
585                                          *      1) err code : LDAP_BUSY ...
586                                          *      2) on err policy : stop service, stop sync, retry
587                                          */
588                                         if ( refreshDeletes == 0 && match < 0 &&
589                                                 err == LDAP_SUCCESS )
590                                         {
591                                                 syncrepl_del_nonpresent( op, si );
592                                         } else {
593                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
594                                                 si->si_presentlist = NULL;
595                                         }
596                                 }
597                                 rc = -2;
598                                 goto done;
599                                 break;
600
601                         case LDAP_RES_INTERMEDIATE:
602                                 rc = ldap_parse_intermediate( si->si_ld, msg,
603                                         &retoid, &retdata, NULL, 0 );
604                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
605                                         int             si_refreshDelete = 0;
606                                         int             si_refreshPresent = 0;
607                                         ber_init2( ber, retdata, LBER_USE_DER );
608
609                                         switch ( si_tag = ber_peek_tag( ber, &len )) {
610                                         ber_tag_t tag;
611                                         case LDAP_TAG_SYNC_NEW_COOKIE:
612                                                 ber_scanf( ber, "tm", &tag, &cookie );
613                                                 break;
614                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
615                                                 si_refreshDelete = 1;
616                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
617                                                 si_refreshPresent = 1;
618                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
619                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
620                                                 {
621                                                         ber_scanf( ber, "m", &cookie );
622                                                         if ( cookie.bv_val ) {
623                                                                 struct berval tmp_bv;
624                                                                 ber_dupbv( &tmp_bv, &cookie );
625                                                                 ber_bvarray_add( &syncCookie.octet_str,
626                                                                         &tmp_bv);
627                                                         }
628                                                         if ( syncCookie.octet_str &&
629                                                                 syncCookie.octet_str[0].bv_val )
630                                                         {
631                                                                 slap_parse_sync_cookie( &syncCookie );
632                                                         }
633                                                 }
634                                                 if ( ber_peek_tag( ber, &len ) ==
635                                                         LDAP_TAG_REFRESHDONE )
636                                                 {
637                                                         ber_scanf( ber, "b", &refreshDone );
638                                                 }
639                                                 ber_scanf( ber, /*"{"*/ "}" );
640                                                 break;
641                                         case LDAP_TAG_SYNC_ID_SET:
642                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
643                                                 if ( ber_peek_tag( ber, &len ) ==
644                                                         LDAP_TAG_SYNC_COOKIE )
645                                                 {
646                                                         ber_scanf( ber, "m", &cookie );
647                                                         if ( cookie.bv_val ) {
648                                                                 struct berval tmp_bv;
649                                                                 ber_dupbv( &tmp_bv, &cookie );
650                                                                 ber_bvarray_add( &syncCookie.octet_str,
651                                                                         &tmp_bv );
652                                                         }
653                                                         if ( syncCookie.octet_str &&
654                                                                 syncCookie.octet_str[0].bv_val )
655                                                         {
656                                                                 slap_parse_sync_cookie( &syncCookie );
657                                                         }
658                                                 }
659                                                 if ( ber_peek_tag( ber, &len ) ==
660                                                         LDAP_TAG_REFRESHDELETES )
661                                                 {
662                                                         ber_scanf( ber, "b", &refreshDeletes );
663                                                 }
664                                                 ber_scanf( ber, "[W]", &syncUUIDs );
665                                                 ber_scanf( ber, /*"{"*/ "}" );
666                                                 for ( i = 0; syncUUIDs[i].bv_val; i++ ) {
667                                                         struct berval *syncuuid_bv;
668                                                         syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
669                                                         slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
670                                                         avl_insert( &si->si_presentlist,
671                                                                 (caddr_t) syncuuid_bv,
672                                                                 syncuuid_cmp, avl_dup_error );
673                                                 }
674                                                 slap_sl_free( syncUUIDs, op->o_tmpmemctx );
675                                                 break;
676                                         default:
677                                         Debug( LDAP_DEBUG_ANY,
678                                                 "do_syncrep2 : unknown syncinfo tag (%ld)\n",
679                                                 (long) si_tag, 0, 0 );
680                                                 ldap_memfree( retoid );
681                                                 ber_bvfree( retdata );
682                                                 continue;
683                                         }
684
685                                         if ( syncCookie_req.ctxcsn == NULL ) {
686                                                 match = -1;
687                                         } else if ( syncCookie.ctxcsn == NULL ) {
688                                                 match = 1;
689                                         } else {
690                                                 value_match( &match, slap_schema.si_ad_entryCSN,
691                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
692                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
693                                                         &syncCookie_req.ctxcsn[0],
694                                                         &syncCookie.ctxcsn[0], &text );
695                                         }
696
697                                         if ( syncCookie.ctxcsn && syncCookie.ctxcsn[0].bv_val &&
698                                                 match < 0 )
699                                         {
700                                                 syncrepl_updateCookie( si, op, psub, &syncCookie);
701                                         }
702
703                                         if ( si_refreshPresent == 1 ) {
704                                                 if ( match < 0 ) {
705                                                         syncrepl_del_nonpresent( op, si );
706                                                 }
707                                         } 
708
709                                         ldap_memfree( retoid );
710                                         ber_bvfree( retdata );
711                                         break;
712
713                                 } else {
714                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
715                                                 "unknown intermediate response (%d)\n",
716                                                 rc, 0, 0 );
717                                         ldap_memfree( retoid );
718                                         ber_bvfree( retdata );
719                                         break;
720                                 }
721                                 break;
722
723                         default:
724                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
725                                         "unknown message\n", 0, 0, 0 );
726                                 break;
727
728                         }
729                         if ( syncCookie.octet_str ) {
730                                 slap_sync_cookie_free( &syncCookie_req, 0 );
731                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
732                                 slap_sync_cookie_free( &syncCookie, 0 );
733                         }
734                 }
735                 ldap_msgfree( res );
736                 res = NULL;
737         }
738
739         if ( rc == -1 ) {
740                 const char *errstr;
741
742                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
743                 errstr = ldap_err2string( rc );
744                 
745                 Debug( LDAP_DEBUG_ANY,
746                         "do_syncrep2 : %s\n", errstr, 0, 0 );
747         }
748
749 done:
750         slap_sync_cookie_free( &syncCookie, 0 );
751         slap_sync_cookie_free( &syncCookie_req, 0 );
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, arg );
836                                 } else {
837                                         connection_client_enable( s );
838                                 } 
839                         } else if ( !first ) {
840                                 dostop = 1;
841                         }
842                 } else {
843                         if ( rc == -2 ) rc = 0;
844                 }
845         }
846
847         /* At this point, we have 4 cases:
848          * 1) for any hard failure, give up and remove this task
849          * 2) for ServerDown, reschedule this task to run
850          * 3) for Refresh and Success, reschedule to run
851          * 4) for Persist and Success, reschedule to defer
852          */
853         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
854
855         if ( ldap_pvt_runqueue_isrunning( &syncrepl_rq, rtask )) {
856                 ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
857         }
858
859         if ( dostop ) {
860                 connection_client_stop( s );
861         }
862
863         if ( rc == LDAP_SUCCESS ) {
864                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
865                         defer = 0;
866                 }
867                 rtask->interval.tv_sec = si->si_interval;
868                 ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, defer );
869                 if ( si->si_retrynum ) {
870                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
871                                 si->si_retrynum[i] = si->si_retrynum_init[i];
872                         }
873                         si->si_retrynum[i] = -2;
874                 }
875         } else {
876                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
877                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
878                                 break;
879                 }
880
881                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
882                         ldap_pvt_runqueue_remove( &syncrepl_rq, rtask );
883                 } else if ( si->si_retrynum[i] >= -1 ) {
884                         if ( si->si_retrynum[i] > 0 )
885                                 si->si_retrynum[i]--;
886                         rtask->interval.tv_sec = si->si_retryinterval[i];
887                         ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, 0 );
888                         slap_wake_listener();
889                 }
890         }
891         
892         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
893
894         return NULL;
895 }
896
897 int
898 syncrepl_message_to_entry(
899         syncinfo_t      *si,
900         Operation       *op,
901         LDAPMessage     *msg,
902         Modifications   **modlist,
903         Entry                   **entry,
904         int             syncstate
905 )
906 {
907         Entry           *e = NULL;
908         BerElement      *ber = NULL;
909         Modifications   tmp;
910         Modifications   *mod;
911         Modifications   **modtail = modlist;
912
913         const char      *text;
914         char txtbuf[SLAP_TEXT_BUFLEN];
915         size_t textlen = sizeof txtbuf;
916
917         struct berval   bdn = {0, NULL}, dn, ndn;
918         int             rc;
919
920         *modlist = NULL;
921
922         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
923                 Debug( LDAP_DEBUG_ANY,
924                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
925                 return -1;
926         }
927
928         op->o_tag = LDAP_REQ_ADD;
929
930         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
931
932         if ( rc != LDAP_SUCCESS ) {
933                 Debug( LDAP_DEBUG_ANY,
934                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
935                 return rc;
936         }
937
938         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
939         ber_dupbv( &op->o_req_dn, &dn );
940         ber_dupbv( &op->o_req_ndn, &ndn );
941         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
942         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
943
944         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
945                 if ( entry )
946                         *entry = NULL;
947                 return LDAP_SUCCESS;
948         }
949
950         if ( entry == NULL ) {
951                 return -1;
952         }
953
954         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
955         *entry = e;
956         e->e_name = op->o_req_dn;
957         e->e_nname = op->o_req_ndn;
958
959         while ( ber_remaining( ber ) ) {
960                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
961                         LBER_ERROR ) || ( tmp.sml_type.bv_val == NULL ))
962                 {
963                         break;
964                 }
965
966                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
967
968                 mod->sml_op = LDAP_MOD_REPLACE;
969                 mod->sml_next = NULL;
970                 mod->sml_desc = NULL;
971                 mod->sml_type = tmp.sml_type;
972                 mod->sml_values = tmp.sml_values;
973                 mod->sml_nvalues = NULL;
974
975                 *modtail = mod;
976                 modtail = &mod->sml_next;
977         }
978
979         if ( *modlist == NULL ) {
980                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
981                         0, 0, 0 );
982                 rc = -1;
983                 goto done;
984         }
985
986         rc = slap_mods_check( *modlist, 1, &text, txtbuf, textlen, NULL );
987
988         if ( rc != LDAP_SUCCESS ) {
989                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
990                         text, 0, 0 );
991                 goto done;
992         }
993
994         /* Strip out dynamically generated attrs */
995         for ( modtail = modlist; *modtail ; ) {
996                 mod = *modtail;
997                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
998                         *modtail = mod->sml_next;
999                         slap_mod_free( &mod->sml_mod, 0 );
1000                         ch_free( mod );
1001                 } else {
1002                         modtail = &mod->sml_next;
1003                 }
1004         }
1005
1006         /* Strip out attrs in exattrs list */
1007         for ( modtail = modlist; *modtail ; ) {
1008                 mod = *modtail;
1009                 if ( ldap_charray_inlist( si->si_exattrs,
1010                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1011                         *modtail = mod->sml_next;
1012                         slap_mod_free( &mod->sml_mod, 0 );
1013                         ch_free( mod );
1014                 } else {
1015                         modtail = &mod->sml_next;
1016                 }
1017         }
1018         
1019         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1020         if( rc != LDAP_SUCCESS ) {
1021                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1022                         text, 0, 0 );
1023         }
1024
1025 done:
1026         ber_free ( ber, 0 );
1027         if ( rc != LDAP_SUCCESS ) {
1028                 if ( e ) {
1029                         entry_free( e );
1030                         *entry = e = NULL;
1031                 }
1032         }
1033
1034         return rc;
1035 }
1036
1037 int
1038 syncrepl_entry(
1039         syncinfo_t* si,
1040         Operation *op,
1041         Entry* entry,
1042         Modifications* modlist,
1043         int syncstate,
1044         struct berval* syncUUID,
1045         struct sync_cookie* syncCookie_req )
1046 {
1047         Backend *be = op->o_bd;
1048         slap_callback   cb = { NULL };
1049         struct berval   *syncuuid_bv = NULL;
1050         struct berval   syncUUID_strrep = BER_BVNULL;
1051         struct berval   uuid_bv = BER_BVNULL;
1052
1053         SlapReply       rs_search = {REP_RESULT};
1054         SlapReply       rs_delete = {REP_RESULT};
1055         SlapReply       rs_add = {REP_RESULT};
1056         SlapReply       rs_modify = {REP_RESULT};
1057         Filter f = {0};
1058         AttributeAssertion ava = {0};
1059         int rc = LDAP_SUCCESS;
1060         int ret = LDAP_SUCCESS;
1061         const char *text;
1062
1063         struct berval pdn = BER_BVNULL;
1064         struct berval org_req_dn = BER_BVNULL;
1065         struct berval org_req_ndn = BER_BVNULL;
1066         struct berval org_dn = BER_BVNULL;
1067         struct berval org_ndn = BER_BVNULL;
1068         int     org_managedsait;
1069
1070         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1071                 syncuuid_bv = ber_dupbv( NULL, syncUUID );
1072                 avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1073                         syncuuid_cmp, avl_dup_error );
1074         }
1075
1076         if ( syncstate == LDAP_SYNC_PRESENT ) {
1077                 return 0;
1078         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1079                 if ( entry == NULL ) {
1080                         return 0;
1081                 }
1082         }
1083
1084         f.f_choice = LDAP_FILTER_EQUALITY;
1085         f.f_ava = &ava;
1086         ava.aa_desc = slap_schema.si_ad_entryUUID;
1087         slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1088         ava.aa_value = *syncUUID;
1089         op->ors_filter = &f;
1090
1091         op->ors_filterstr.bv_len = (sizeof("entryUUID=")-1) + syncUUID->bv_len;
1092         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1093                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1094         AC_MEMCPY( op->ors_filterstr.bv_val, "entryUUID=", sizeof("entryUUID=")-1 );
1095         AC_MEMCPY( &op->ors_filterstr.bv_val[sizeof("entryUUID=")-1],
1096                 syncUUID->bv_val, syncUUID->bv_len );
1097         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1098
1099         op->o_tag = LDAP_REQ_SEARCH;
1100         op->ors_scope = LDAP_SCOPE_SUBTREE;
1101
1102         /* get syncrepl cookie of shadow replica from subentry */
1103         op->o_req_dn = si->si_base;
1104         op->o_req_ndn = si->si_base;
1105
1106         op->o_time = slap_get_time();
1107         op->ors_tlimit = SLAP_NO_LIMIT;
1108         op->ors_slimit = 1;
1109
1110         op->ors_attrs = slap_anlist_no_attrs;
1111         op->ors_attrsonly = 1;
1112
1113         /* set callback function */
1114         op->o_callback = &cb;
1115         cb.sc_response = dn_callback;
1116         cb.sc_private = si;
1117
1118         si->si_syncUUID_ndn.bv_val = NULL;
1119
1120         if ( limits_check( op, &rs_search ) == 0 ) {
1121                 rc = be->be_search( op, &rs_search );
1122         }
1123
1124         if ( op->ors_filterstr.bv_val ) {
1125                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1126         }
1127
1128         cb.sc_response = null_callback;
1129         cb.sc_private = si;
1130
1131         if ( rs_search.sr_err == LDAP_SUCCESS && si->si_syncUUID_ndn.bv_val ) {
1132                 char *subseq_ptr;
1133
1134                 if ( syncstate != LDAP_SYNC_DELETE ) {
1135                         op->o_no_psearch = 1;
1136                 }
1137
1138                 ber_dupbv( &op->o_sync_csn, syncCookie_req->ctxcsn );
1139                 if ( op->o_sync_csn.bv_val ) {
1140                         subseq_ptr = strstr( op->o_sync_csn.bv_val, "#0000" );
1141                         subseq_ptr += 4;
1142                         *subseq_ptr = '1';
1143                 }
1144                 
1145                 op->o_req_dn = si->si_syncUUID_ndn;
1146                 op->o_req_ndn = si->si_syncUUID_ndn;
1147                 op->o_tag = LDAP_REQ_DELETE;
1148                 rc = be->be_delete( op, &rs_delete );
1149
1150                 org_req_dn = op->o_req_dn;
1151                 org_req_ndn = op->o_req_ndn;
1152                 org_dn = op->o_dn;
1153                 org_ndn = op->o_ndn;
1154                 org_managedsait = get_manageDSAit( op );
1155                 op->o_dn = op->o_bd->be_rootdn;
1156                 op->o_ndn = op->o_bd->be_rootndn;
1157                 op->o_managedsait = 1;
1158
1159                 while ( rs_delete.sr_err == LDAP_SUCCESS && op->o_delete_glue_parent ) {
1160                         op->o_delete_glue_parent = 0;
1161                         if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1162                                 slap_callback cb = { NULL };
1163                                 cb.sc_response = slap_null_cb;
1164                                 dnParent( &op->o_req_ndn, &pdn );
1165                                 op->o_req_dn = pdn;
1166                                 op->o_req_ndn = pdn;
1167                                 op->o_callback = &cb;
1168                                 op->o_bd->be_delete( op, &rs_delete );
1169                         } else {
1170                                 break;
1171                     }
1172                 }
1173
1174                 op->o_managedsait = org_managedsait;
1175                 op->o_dn = org_dn;
1176                 op->o_ndn = org_ndn;
1177                 op->o_req_dn = org_req_dn;
1178                 op->o_req_ndn = org_req_ndn;
1179                 op->o_delete_glue_parent = 0;
1180
1181                 op->o_no_psearch = 0;
1182         }
1183
1184         switch ( syncstate ) {
1185         case LDAP_SYNC_ADD:
1186         case LDAP_SYNC_MODIFY:
1187                 if ( rs_search.sr_err == LDAP_SUCCESS ||
1188                          rs_search.sr_err == LDAP_REFERRAL ||
1189                          rs_search.sr_err == LDAP_NO_SUCH_OBJECT ||
1190                          rs_search.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF )
1191                 {
1192                         attr_delete( &entry->e_attrs, slap_schema.si_ad_entryUUID );
1193                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1194                                 &syncUUID_strrep, syncUUID );
1195
1196                         op->o_tag = LDAP_REQ_ADD;
1197                         op->ora_e = entry;
1198                         op->o_req_dn = entry->e_name;
1199                         op->o_req_ndn = entry->e_nname;
1200
1201                         rc = be->be_add( op, &rs_add );
1202
1203                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1204                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS &&
1205                                          rs_search.sr_err != LDAP_NO_SUCH_OBJECT ) {
1206                                         Modifications *mod;
1207                                         Modifications *modtail = modlist;
1208
1209                                         assert( modlist );
1210
1211                                         for ( mod = modlist; mod != NULL; mod = mod->sml_next ) {
1212                                                 modtail = mod;
1213                                         }
1214
1215                                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1216                                         ber_dupbv( &uuid_bv, syncUUID );
1217                                         mod->sml_op = LDAP_MOD_REPLACE;
1218                                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1219                                         mod->sml_type = mod->sml_desc->ad_cname;
1220                                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1221                                         modtail->sml_next = mod;
1222                                         
1223                                         op->o_tag = LDAP_REQ_MODIFY;
1224                                         op->orm_modlist = modlist;
1225                                         op->o_req_dn = entry->e_name;
1226                                         op->o_req_ndn = entry->e_nname;
1227
1228                                         rc = be->be_modify( op, &rs_modify );
1229                                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1230                                                 Debug( LDAP_DEBUG_ANY,
1231                                                         "syncrepl_entry : be_modify failed (%d)\n",
1232                                                         rs_modify.sr_err, 0, 0 );
1233                                         }
1234                                         ret = 1;
1235                                         goto done;
1236                                 } else if ( rs_modify.sr_err == LDAP_REFERRAL ||
1237                                                         rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1238                                         syncrepl_add_glue( op, entry );
1239                                         ret = 0;
1240                                         goto done;
1241                                 } else {
1242                                         Debug( LDAP_DEBUG_ANY,
1243                                                 "syncrepl_entry : be_add failed (%d)\n",
1244                                                 rs_add.sr_err, 0, 0 );
1245                                         ret = 1;
1246                                         goto done;
1247                                 }
1248                         } else {
1249                                 be_entry_release_w( op, entry );
1250                                 ret = 0;
1251                                 goto done;
1252                         }
1253                 } else {
1254                         Debug( LDAP_DEBUG_ANY,
1255                                 "syncrepl_entry : be_search failed (%d)\n",
1256                                 rs_search.sr_err, 0, 0 );
1257                         ret = 1;
1258                         goto done;
1259                 }
1260
1261         case LDAP_SYNC_DELETE :
1262                 /* Already deleted */
1263                 ret = 0;
1264                 goto done;
1265
1266         default :
1267                 Debug( LDAP_DEBUG_ANY,
1268                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1269                 ret = 1;
1270                 goto done;
1271         }
1272
1273 done :
1274
1275         if ( syncUUID_strrep.bv_val ) {
1276                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1277         }
1278         if ( si->si_syncUUID_ndn.bv_val ) {
1279                 ch_free( si->si_syncUUID_ndn.bv_val );
1280         }
1281         return ret;
1282 }
1283
1284 static struct berval gcbva[] = {
1285         BER_BVC("top"),
1286         BER_BVC("glue"),
1287         BER_BVNULL
1288 };
1289
1290 static void
1291 syncrepl_del_nonpresent(
1292         Operation *op,
1293         syncinfo_t *si )
1294 {
1295         Backend* be = op->o_bd;
1296         slap_callback   cb = { NULL };
1297         SlapReply       rs_search = {REP_RESULT};
1298         SlapReply       rs_delete = {REP_RESULT};
1299         SlapReply       rs_modify = {REP_RESULT};
1300         struct nonpresent_entry *np_list, *np_prev;
1301         int rc;
1302         Modifications *ml;
1303         Modifications *mlnext;
1304         Modifications *mod;
1305         Modifications *modlist = NULL;
1306         Modifications **modtail = &modlist;
1307         Attribute       *attr;
1308         AttributeName   an[2];
1309
1310         struct berval pdn = BER_BVNULL;
1311         struct berval org_req_dn = BER_BVNULL;
1312         struct berval org_req_ndn = BER_BVNULL;
1313         struct berval org_dn = BER_BVNULL;
1314         struct berval org_ndn = BER_BVNULL;
1315         int     org_managedsait;
1316
1317         op->o_req_dn = si->si_base;
1318         op->o_req_ndn = si->si_base;
1319
1320         cb.sc_response = nonpresent_callback;
1321         cb.sc_private = si;
1322
1323         op->o_callback = &cb;
1324         op->o_tag = LDAP_REQ_SEARCH;
1325         op->ors_scope = si->si_scope;
1326         op->ors_deref = LDAP_DEREF_NEVER;
1327         op->o_time = slap_get_time();
1328         op->ors_tlimit = SLAP_NO_LIMIT;
1329         op->ors_slimit = SLAP_NO_LIMIT;
1330
1331         memset( &an[0], 0, 2 * sizeof( AttributeName ) );
1332         an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1333         an[0].an_desc = slap_schema.si_ad_entryUUID;
1334         op->ors_attrs = an;
1335
1336         op->ors_attrsonly = 0;
1337         op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
1338         op->ors_filterstr = si->si_filterstr;
1339
1340         op->o_nocaching = 1;
1341         op->o_managedsait = 0;
1342
1343         if ( limits_check( op, &rs_search ) == 0 ) {
1344                 rc = be->be_search( op, &rs_search );
1345         }
1346
1347         op->o_managedsait = 1;
1348         op->o_nocaching = 0;
1349
1350         if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
1351
1352         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
1353                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
1354                 while ( np_list != NULL ) {
1355                         LDAP_LIST_REMOVE( np_list, npe_link );
1356                         np_prev = np_list;
1357                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
1358                         op->o_tag = LDAP_REQ_DELETE;
1359                         op->o_callback = &cb;
1360                         cb.sc_response = null_callback;
1361                         cb.sc_private = si;
1362                         op->o_req_dn = *np_prev->npe_name;
1363                         op->o_req_ndn = *np_prev->npe_nname;
1364                         rc = op->o_bd->be_delete( op, &rs_delete );
1365
1366                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
1367                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1368                                 mod->sml_op = LDAP_MOD_REPLACE;
1369                                 mod->sml_desc = slap_schema.si_ad_objectClass;
1370                                 mod->sml_type = mod->sml_desc->ad_cname;
1371                                 mod->sml_values = &gcbva[0];
1372                                 *modtail = mod;
1373                                 modtail = &mod->sml_next;
1374
1375                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1376                                 mod->sml_op = LDAP_MOD_REPLACE;
1377                                 mod->sml_desc = slap_schema.si_ad_structuralObjectClass;
1378                                 mod->sml_type = mod->sml_desc->ad_cname;
1379                                 mod->sml_values = &gcbva[1];
1380                                 *modtail = mod;
1381                                 modtail = &mod->sml_next;
1382
1383                                 op->o_tag = LDAP_REQ_MODIFY;
1384                                 op->orm_modlist = modlist;
1385
1386                                 rc = be->be_modify( op, &rs_modify );
1387
1388                                 for ( ml = modlist; ml != NULL; ml = mlnext ) {
1389                                         mlnext = ml->sml_next;
1390                                         free( ml );
1391                                 }
1392                         }
1393
1394                         org_req_dn = op->o_req_dn;
1395                         org_req_ndn = op->o_req_ndn;
1396                         org_dn = op->o_dn;
1397                         org_ndn = op->o_ndn;
1398                         org_managedsait = get_manageDSAit( op );
1399                         op->o_dn = op->o_bd->be_rootdn;
1400                         op->o_ndn = op->o_bd->be_rootndn;
1401                         op->o_managedsait = 1;
1402
1403                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
1404                                         op->o_delete_glue_parent ) {
1405                                 op->o_delete_glue_parent = 0;
1406                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1407                                         slap_callback cb = { NULL };
1408                                         cb.sc_response = slap_null_cb;
1409                                         dnParent( &op->o_req_ndn, &pdn );
1410                                         op->o_req_dn = pdn;
1411                                         op->o_req_ndn = pdn;
1412                                         op->o_callback = &cb;
1413                                         /* give it a root privil ? */
1414                                         op->o_bd->be_delete( op, &rs_delete );
1415                                 } else {
1416                                         break;
1417                             }
1418                         }
1419
1420                         op->o_managedsait = org_managedsait;
1421                         op->o_dn = org_dn;
1422                         op->o_ndn = org_ndn;
1423                         op->o_req_dn = org_req_dn;
1424                         op->o_req_ndn = org_req_ndn;
1425                         op->o_delete_glue_parent = 0;
1426
1427                         ber_bvfree( np_prev->npe_name );
1428                         ber_bvfree( np_prev->npe_nname );
1429                         op->o_req_dn.bv_val = NULL;
1430                         op->o_req_ndn.bv_val = NULL;
1431                         ch_free( np_prev );
1432                 }
1433         }
1434
1435         return;
1436 }
1437
1438 void
1439 syncrepl_add_glue(
1440         Operation* op,
1441         Entry *e )
1442 {
1443         Backend *be = op->o_bd;
1444         slap_callback cb = { NULL };
1445         Attribute       *a;
1446         int     rc;
1447         int suffrdns;
1448         int i;
1449         struct berval dn = {0, NULL};
1450         struct berval ndn = {0, NULL};
1451         Entry   *glue;
1452         SlapReply       rs_add = {REP_RESULT};
1453         char    *ptr, *comma;
1454
1455         op->o_tag = LDAP_REQ_ADD;
1456         op->o_callback = &cb;
1457         cb.sc_response = null_callback;
1458         cb.sc_private = NULL;
1459
1460         dn = e->e_name;
1461         ndn = e->e_nname;
1462
1463         /* count RDNs in suffix */
1464         if ( be->be_nsuffix[0].bv_len ) {
1465                 for (i=0, ptr=be->be_nsuffix[0].bv_val; ptr; ptr=strchr( ptr, ',' )) {
1466                         ptr++;
1467                         i++;
1468                 }
1469                 suffrdns = i;
1470         } else {
1471                 /* suffix is "" */
1472                 suffrdns = 0;
1473         }
1474
1475         /* Start with BE suffix */
1476         for ( i = 0, ptr = NULL; i < suffrdns; i++ ) {
1477                 comma = strrchr(dn.bv_val, ',');
1478                 if ( ptr ) *ptr = ',';
1479                 if ( comma ) *comma = '\0';
1480                 ptr = comma;
1481         }
1482         if ( ptr ) {
1483                 *ptr++ = ',';
1484                 dn.bv_len -= ptr - dn.bv_val;
1485                 dn.bv_val = ptr;
1486         }
1487         /* the normalizedDNs are always the same length, no counting
1488          * required.
1489          */
1490         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
1491                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
1492                 ndn.bv_len = be->be_nsuffix[0].bv_len;
1493         }
1494
1495         while ( ndn.bv_val > e->e_nname.bv_val ) {
1496                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
1497                 ber_dupbv( &glue->e_name, &dn );
1498                 ber_dupbv( &glue->e_nname, &ndn );
1499
1500                 a = ch_calloc( 1, sizeof( Attribute ));
1501                 a->a_desc = slap_schema.si_ad_objectClass;
1502
1503                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1504                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
1505                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
1506                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
1507
1508                 a->a_nvals = a->a_vals;
1509
1510                 a->a_next = glue->e_attrs;
1511                 glue->e_attrs = a;
1512
1513                 a = ch_calloc( 1, sizeof( Attribute ));
1514                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1515
1516                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1517                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
1518                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
1519
1520                 a->a_nvals = a->a_vals;
1521
1522                 a->a_next = glue->e_attrs;
1523                 glue->e_attrs = a;
1524
1525                 op->o_req_dn = glue->e_name;
1526                 op->o_req_ndn = glue->e_nname;
1527                 op->ora_e = glue;
1528                 rc = be->be_add ( op, &rs_add );
1529                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
1530                         be_entry_release_w( op, glue );
1531                 } else {
1532                 /* incl. ALREADY EXIST */
1533                         entry_free( glue );
1534                 }
1535
1536                 /* Move to next child */
1537                 for (ptr = dn.bv_val-2; ptr > e->e_name.bv_val && *ptr != ','; ptr--) {
1538                         /* empty */
1539                 }
1540                 if ( ptr == e->e_name.bv_val ) break;
1541                 dn.bv_val = ++ptr;
1542                 dn.bv_len = e->e_name.bv_len - (ptr-e->e_name.bv_val);
1543                 for( ptr = ndn.bv_val-2;
1544                         ptr > e->e_nname.bv_val && *ptr != ',';
1545                         ptr--)
1546                 {
1547                         /* empty */
1548                 }
1549                 ndn.bv_val = ++ptr;
1550                 ndn.bv_len = e->e_nname.bv_len - (ptr-e->e_nname.bv_val);
1551         }
1552
1553         op->o_req_dn = e->e_name;
1554         op->o_req_ndn = e->e_nname;
1555         op->ora_e = e;
1556         rc = be->be_add ( op, &rs_add );
1557         if ( rs_add.sr_err == LDAP_SUCCESS ) {
1558                 be_entry_release_w( op, e );
1559         } else {
1560                 entry_free( e );
1561         }
1562
1563         return;
1564 }
1565
1566 static struct berval ocbva[] = {
1567         BER_BVC("top"),
1568         BER_BVC("subentry"),
1569         BER_BVC("syncConsumerSubentry"),
1570         BER_BVNULL
1571 };
1572
1573 static struct berval cnbva[] = {
1574         BER_BVNULL,
1575         BER_BVNULL
1576 };
1577
1578 static struct berval ssbva[] = {
1579         BER_BVC("{}"),
1580         BER_BVNULL
1581 };
1582
1583 static struct berval scbva[] = {
1584         BER_BVNULL,
1585         BER_BVNULL
1586 };
1587
1588 void
1589 syncrepl_updateCookie(
1590         syncinfo_t *si,
1591         Operation *op,
1592         struct berval *pdn,
1593         struct sync_cookie *syncCookie )
1594 {
1595         Backend *be = op->o_bd;
1596         Modifications *ml;
1597         Modifications *mlnext;
1598         Modifications *mod;
1599         Modifications *modlist = NULL;
1600         Modifications **modtail = &modlist;
1601
1602         const char      *text;
1603         char txtbuf[SLAP_TEXT_BUFLEN];
1604         size_t textlen = sizeof txtbuf;
1605
1606         Entry* e = NULL;
1607         int rc;
1608
1609         char syncrepl_cbuf[sizeof(CN_STR SYNCREPL_STR)];
1610         struct berval slap_syncrepl_dn_bv = BER_BVNULL;
1611         struct berval slap_syncrepl_cn_bv = BER_BVNULL;
1612         
1613         slap_callback cb = { NULL };
1614         SlapReply       rs_add = {REP_RESULT};
1615         SlapReply       rs_modify = {REP_RESULT};
1616
1617         slap_sync_cookie_free( &si->si_syncCookie, 0 );
1618         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
1619
1620         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1621         mod->sml_op = LDAP_MOD_REPLACE;
1622         mod->sml_desc = slap_schema.si_ad_objectClass;
1623         mod->sml_type = mod->sml_desc->ad_cname;
1624         mod->sml_values = ocbva;
1625         *modtail = mod;
1626         modtail = &mod->sml_next;
1627
1628         ber_dupbv( &cnbva[0], (struct berval *) &slap_syncrepl_bvc );
1629         assert( si->si_rid < 1000 );
1630         cnbva[0].bv_len = snprintf( cnbva[0].bv_val,
1631                 slap_syncrepl_bvc.bv_len + 1,
1632                 "syncrepl%ld", si->si_rid );
1633         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1634         mod->sml_op = LDAP_MOD_REPLACE;
1635         mod->sml_desc = slap_schema.si_ad_cn;
1636         mod->sml_type = mod->sml_desc->ad_cname;
1637         mod->sml_values = cnbva;
1638         *modtail = mod;
1639         modtail = &mod->sml_next;
1640
1641         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1642         mod->sml_op = LDAP_MOD_REPLACE;
1643         mod->sml_desc = slap_schema.si_ad_subtreeSpecification;
1644         mod->sml_type = mod->sml_desc->ad_cname;
1645         mod->sml_values = ssbva;
1646         *modtail = mod;
1647         modtail = &mod->sml_next;
1648
1649         /* Keep this last, so we can avoid touching the previous
1650          * attributes unnecessarily.
1651          */
1652         if ( scbva[0].bv_val ) ch_free( scbva[0].bv_val );
1653         ber_dupbv( &scbva[0], &si->si_syncCookie.octet_str[0] );
1654         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1655         mod->sml_op = LDAP_MOD_REPLACE;
1656         mod->sml_desc = slap_schema.si_ad_syncreplCookie;
1657         mod->sml_type = mod->sml_desc->ad_cname;
1658         mod->sml_values = scbva;
1659         *modtail = mod;
1660         modtail = &mod->sml_next;
1661
1662         mlnext = mod;
1663
1664         op->o_tag = LDAP_REQ_ADD;
1665         rc = slap_mods_opattrs( op, modlist, modtail,
1666                  &text, txtbuf, textlen, 0 );
1667
1668         for ( ml = modlist; ml != NULL; ml = ml->sml_next ) {
1669                 ml->sml_op = LDAP_MOD_REPLACE;
1670         }
1671
1672         if( rc != LDAP_SUCCESS ) {
1673                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods opattrs (%s)\n",
1674                          text, 0, 0 );
1675         }
1676
1677         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1678
1679         slap_syncrepl_cn_bv.bv_val = syncrepl_cbuf;
1680         assert( si->si_rid < 1000 );
1681         slap_syncrepl_cn_bv.bv_len = snprintf( slap_syncrepl_cn_bv.bv_val,
1682                 slap_syncrepl_cn_bvc.bv_len + 1,
1683                 "cn=syncrepl%ld", si->si_rid );
1684
1685         build_new_dn( &slap_syncrepl_dn_bv, pdn, &slap_syncrepl_cn_bv,
1686                 op->o_tmpmemctx );
1687         ber_dupbv( &e->e_name, &slap_syncrepl_dn_bv );
1688         ber_dupbv( &e->e_nname, &slap_syncrepl_dn_bv );
1689
1690         if ( slap_syncrepl_dn_bv.bv_val ) {
1691                 slap_sl_free( slap_syncrepl_dn_bv.bv_val, op->o_tmpmemctx );
1692         }
1693
1694         e->e_attrs = NULL;
1695
1696         rc = slap_mods2entry( modlist, &e, 1, 1, &text, txtbuf, textlen );
1697
1698         if( rc != LDAP_SUCCESS ) {
1699                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods2entry (%s)\n",
1700                          text, 0, 0 );
1701         }
1702
1703         cb.sc_response = null_callback;
1704         cb.sc_private = si;
1705
1706         op->o_callback = &cb;
1707         op->o_req_dn = e->e_name;
1708         op->o_req_ndn = e->e_nname;
1709
1710         /* update persistent cookie */
1711 update_cookie_retry:
1712         op->o_tag = LDAP_REQ_MODIFY;
1713         /* Just modify the cookie value, not the entire entry */
1714         op->orm_modlist = mod;
1715         rc = be->be_modify( op, &rs_modify );
1716
1717         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1718                 if ( rs_modify.sr_err == LDAP_REFERRAL ||
1719                          rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1720                         op->o_tag = LDAP_REQ_ADD;
1721                         op->ora_e = e;
1722                         rc = be->be_add( op, &rs_add );
1723                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1724                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS ) {
1725                                         goto update_cookie_retry;
1726                                 } else if ( rs_add.sr_err == LDAP_REFERRAL ||
1727                                                         rs_add.sr_err == LDAP_NO_SUCH_OBJECT ) {
1728                                         Debug( LDAP_DEBUG_ANY,
1729                                                 "cookie will be non-persistent\n",
1730                                                 0, 0, 0 );
1731                                 } else {
1732                                         Debug( LDAP_DEBUG_ANY,
1733                                                 "be_add failed (%d)\n", rs_add.sr_err, 0, 0 );
1734                                 }
1735                         } else {
1736                                 be_entry_release_w( op, e );
1737                                 goto done;
1738                         }
1739                 } else {
1740                         Debug( LDAP_DEBUG_ANY,
1741                                 "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
1742                 }
1743         }
1744
1745         if ( e != NULL ) {
1746                 entry_free( e );
1747         }
1748
1749 done :
1750
1751         if ( cnbva[0].bv_val ) {
1752                 ch_free( cnbva[0].bv_val );
1753                 cnbva[0].bv_val = NULL;
1754         }
1755         if ( scbva[0].bv_val ) {
1756                 ch_free( scbva[0].bv_val );
1757                 scbva[0].bv_val = NULL;
1758         }
1759
1760         if ( mlnext->sml_next ) {
1761                 slap_mods_free( mlnext->sml_next );
1762                 mlnext->sml_next = NULL;
1763         }
1764
1765         for (ml = modlist ; ml != NULL; ml = mlnext ) {
1766                 mlnext = ml->sml_next;
1767                 free( ml );
1768         }
1769
1770         return;
1771 }
1772
1773 int
1774 syncrepl_isupdate( Operation *op )
1775 {
1776         return ( syncrepl_isupdate_dn( op->o_bd, &op->o_ndn ));
1777 }
1778
1779 int
1780 syncrepl_isupdate_dn(
1781         Backend*                be,
1782         struct berval*  ndn )
1783 {
1784         syncinfo_t*     si;
1785         int                     ret = 0;
1786
1787         if ( !LDAP_STAILQ_EMPTY( &be->be_syncinfo )) {
1788                 LDAP_STAILQ_FOREACH( si, &be->be_syncinfo, si_next ) {
1789                         if ( ( ret = dn_match( &si->si_updatedn, ndn ) ) ) {
1790                                 return ret;
1791                         }
1792                 }
1793         }
1794         return 0;
1795 }
1796
1797 static int
1798 dn_callback(
1799         Operation*      op,
1800         SlapReply*      rs )
1801 {
1802         syncinfo_t *si = op->o_callback->sc_private;
1803
1804         if ( rs->sr_type == REP_SEARCH ) {
1805                 if ( si->si_syncUUID_ndn.bv_val != NULL ) {
1806                         Debug( LDAP_DEBUG_ANY,
1807                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1808                 } else {
1809                         ber_dupbv_x( &si->si_syncUUID_ndn, &rs->sr_entry->e_nname, NULL );
1810                 }
1811         } else if ( rs->sr_type == REP_RESULT ) {
1812                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
1813                         Debug( LDAP_DEBUG_ANY,
1814                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1815                 }
1816         }
1817
1818         return LDAP_SUCCESS;
1819 }
1820
1821 static int
1822 nonpresent_callback(
1823         Operation*      op,
1824         SlapReply*      rs )
1825 {
1826         syncinfo_t *si = op->o_callback->sc_private;
1827         Attribute *a;
1828         int count = 0;
1829         struct berval* present_uuid = NULL;
1830         struct nonpresent_entry *np_entry;
1831
1832         if ( rs->sr_type == REP_RESULT ) {
1833                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
1834                 si->si_presentlist = NULL;
1835
1836         } else if ( rs->sr_type == REP_SEARCH ) {
1837                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
1838
1839                 if ( a == NULL ) return 0;
1840
1841                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
1842                         syncuuid_cmp );
1843
1844                 if ( present_uuid == NULL ) {
1845                         np_entry = (struct nonpresent_entry *)
1846                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
1847                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
1848                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
1849                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
1850
1851                 } else {
1852                         avl_delete( &si->si_presentlist,
1853                                         &a->a_nvals[0], syncuuid_cmp );
1854                         ch_free( present_uuid->bv_val );
1855                         ch_free( present_uuid );
1856                 }
1857         }
1858         return LDAP_SUCCESS;
1859 }
1860
1861 static int
1862 null_callback(
1863         Operation*      op,
1864         SlapReply*      rs )
1865 {
1866         if ( rs->sr_err != LDAP_SUCCESS &&
1867                 rs->sr_err != LDAP_REFERRAL &&
1868                 rs->sr_err != LDAP_ALREADY_EXISTS &&
1869                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
1870                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
1871         {
1872                 Debug( LDAP_DEBUG_ANY,
1873                         "null_callback : error code 0x%x\n",
1874                         rs->sr_err, 0, 0 );
1875         }
1876         return LDAP_SUCCESS;
1877 }
1878
1879 Entry *
1880 slap_create_syncrepl_entry(
1881         Backend *be,
1882         struct berval *context_csn,
1883         struct berval *rdn,
1884         struct berval *cn )
1885 {
1886         Entry* e;
1887
1888         struct berval bv;
1889
1890         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1891
1892         attr_merge( e, slap_schema.si_ad_objectClass, ocbva, NULL );
1893
1894         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
1895                 &ocbva[1], NULL );
1896
1897         attr_merge_one( e, slap_schema.si_ad_cn, cn, NULL );
1898
1899         if ( context_csn ) {
1900                 attr_merge_one( e, slap_schema.si_ad_syncreplCookie,
1901                         context_csn, NULL );
1902         }
1903
1904         bv.bv_val = "{}";
1905         bv.bv_len = sizeof("{}")-1;
1906         attr_merge_one( e, slap_schema.si_ad_subtreeSpecification, &bv, NULL );
1907
1908         build_new_dn( &e->e_name, &be->be_nsuffix[0], rdn, NULL );
1909         ber_dupbv( &e->e_nname, &e->e_name );
1910
1911         return e;
1912 }
1913
1914 struct berval *
1915 slap_uuidstr_from_normalized(
1916         struct berval* uuidstr,
1917         struct berval* normalized,
1918         void *ctx )
1919 {
1920         struct berval *new;
1921         unsigned char nibble;
1922         int i, d = 0;
1923
1924         if ( normalized == NULL ) return NULL;
1925         if ( normalized->bv_len != 16 ) return NULL;
1926
1927         if ( uuidstr ) {
1928                 new = uuidstr;
1929         } else {
1930                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
1931         }
1932
1933         new->bv_len = 36;
1934
1935         if (( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx )) == NULL) {
1936                 if ( !uuidstr ) slap_sl_free( new, ctx );
1937                 return NULL;
1938         }
1939
1940         for ( i = 0; i < 16; i++ ) {
1941                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
1942                         new->bv_val[(i<<1)+d] = '-';
1943                         d += 1;
1944                 }
1945
1946                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
1947                 if ( nibble < 10 ) {
1948                         new->bv_val[(i<<1)+d] = nibble + '0';
1949                 } else {
1950                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
1951                 }
1952
1953                 nibble = (normalized->bv_val[i]) & 0xF;
1954                 if ( nibble < 10 ) {
1955                         new->bv_val[(i<<1)+d+1] = nibble + '0';
1956                 } else {
1957                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
1958                 }
1959         }
1960
1961         new->bv_val[new->bv_len] = '\0';
1962         return new;
1963 }
1964
1965 static int
1966 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
1967 {
1968         const struct berval *uuid1 = v_uuid1;
1969         const struct berval *uuid2 = v_uuid2;
1970         int rc = uuid1->bv_len - uuid2->bv_len;
1971         if ( rc ) return rc;
1972         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
1973 }
1974
1975 static void
1976 avl_ber_bvfree( void *bv )
1977 {
1978         if( bv == NULL ) return;
1979         if ( ((struct berval *)bv)->bv_val != NULL ) {
1980                 ch_free( ((struct berval *)bv)->bv_val );
1981         }
1982         ch_free( (char *) bv );
1983 }
1984
1985 void
1986 syncinfo_free( syncinfo_t *sie )
1987 {
1988         if ( sie->si_provideruri ) {
1989                 ch_free( sie->si_provideruri );
1990         }
1991         if ( sie->si_provideruri_bv ) {
1992                 ber_bvarray_free( sie->si_provideruri_bv );
1993         }
1994         if ( sie->si_updatedn.bv_val ) {
1995                 ch_free( sie->si_updatedn.bv_val );
1996         }
1997         if ( sie->si_binddn ) {
1998                 ch_free( sie->si_binddn );
1999         }
2000         if ( sie->si_passwd ) {
2001                 ch_free( sie->si_passwd );
2002         }
2003         if ( sie->si_saslmech ) {
2004                 ch_free( sie->si_saslmech );
2005         }
2006         if ( sie->si_secprops ) {
2007                 ch_free( sie->si_secprops );
2008         }
2009         if ( sie->si_realm ) {
2010                 ch_free( sie->si_realm );
2011         }
2012         if ( sie->si_authcId ) {
2013                 ch_free( sie->si_authcId );
2014         }
2015         if ( sie->si_authzId ) {
2016                 ch_free( sie->si_authzId );
2017         }
2018         if ( sie->si_filterstr.bv_val ) {
2019                 ch_free( sie->si_filterstr.bv_val );
2020         }
2021         if ( sie->si_base.bv_val ) {
2022                 ch_free( sie->si_base.bv_val );
2023         }
2024         if ( sie->si_attrs ) {
2025                 int i = 0;
2026                 while ( sie->si_attrs[i] != NULL ) {
2027                         ch_free( sie->si_attrs[i] );
2028                         i++;
2029                 }
2030                 ch_free( sie->si_attrs );
2031         }
2032         if ( sie->si_exattrs ) {
2033                 int i = 0;
2034                 while ( sie->si_exattrs[i] != NULL ) {
2035                         ch_free( sie->si_exattrs[i] );
2036                         i++;
2037                 }
2038                 ch_free( sie->si_exattrs );
2039         }
2040         if ( sie->si_retryinterval ) {
2041                 ch_free( sie->si_retryinterval );
2042         }
2043         if ( sie->si_retrynum ) {
2044                 ch_free( sie->si_retrynum );
2045         }
2046         if ( sie->si_retrynum_init ) {
2047                 ch_free( sie->si_retrynum_init );
2048         }
2049         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2050         if ( sie->si_syncUUID_ndn.bv_val ) {
2051                 ch_free( sie->si_syncUUID_ndn.bv_val );
2052         }
2053         if ( sie->si_presentlist ) {
2054             avl_free( sie->si_presentlist, avl_ber_bvfree );
2055         }
2056         if ( sie->si_ld ) {
2057                 ldap_ld_free( sie->si_ld, 1, NULL, NULL );
2058         }
2059         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2060                 struct nonpresent_entry* npe;
2061                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2062                 LDAP_LIST_REMOVE( npe, npe_link );
2063                 if ( npe->npe_name ) {
2064                         if ( npe->npe_name->bv_val ) {
2065                                 ch_free( npe->npe_name->bv_val );
2066                         }
2067                         ch_free( npe->npe_name );
2068                 }
2069                 if ( npe->npe_nname ) {
2070                         if ( npe->npe_nname->bv_val ) {
2071                                 ch_free( npe->npe_nname->bv_val );
2072                         }
2073                         ch_free( npe->npe_nname );
2074                 }
2075                 ch_free( npe );
2076         }
2077         ch_free( sie );
2078 }