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