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