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