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