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