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