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