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