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