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