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