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