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