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