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