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