]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
TLS SSF does not imply a transport_ssf.
[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                                         entry = NULL;
558                                 }
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         op.o_dn = si->si_updatedn;
861         op.o_ndn = si->si_updatedn;
862         op.o_managedsait = 1;
863         op.o_bd = si->si_be;
864
865         op.o_sync_state.ctxcsn = NULL;
866         op.o_sync_state.sid = -1;
867         op.o_sync_state.octet_str = NULL;
868         op.o_sync_slog_size = -1;
869         LDAP_STAILQ_FIRST( &op.o_sync_slog_list ) = NULL;
870         op.o_sync_slog_list.stqh_last = &LDAP_STAILQ_FIRST(&op.o_sync_slog_list);
871
872         /* Establish session, do search */
873         if ( !si->si_ld ) {
874                 first = 1;
875                 rc = do_syncrep1( &op, si );
876         }
877
878         /* Process results */
879         if ( rc == LDAP_SUCCESS ) {
880                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
881
882                 rc = do_syncrep2( &op, si );
883
884                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
885                         /* If we succeeded, enable the connection for further listening.
886                          * If we failed, tear down the connection and reschedule.
887                          */
888                         if ( rc == LDAP_SUCCESS ) {
889                                 if ( first ) {
890                                         rc = connection_client_setup( s, do_syncrepl,
891                                                 arg );
892                                 } else {
893                                         connection_client_enable( s );
894                                 } 
895                         } else if ( !first ) {
896                                 dostop = 1;
897                         }
898                 } else {
899                         if ( rc == -2 ) rc = 0;
900                 }
901         }
902
903         /* At this point, we have 4 cases:
904          * 1) for any hard failure, give up and remove this task
905          * 2) for ServerDown, reschedule this task to run
906          * 3) for Refresh and Success, reschedule to run
907          * 4) for Persist and Success, reschedule to defer
908          */
909         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
910
911         if ( ldap_pvt_runqueue_isrunning( &syncrepl_rq, rtask )) {
912                 ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
913         }
914
915         if ( dostop ) {
916                 connection_client_stop( s );
917         }
918
919         if ( rc == LDAP_SUCCESS ) {
920                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
921                         defer = 0;
922                 }
923                 rtask->interval.tv_sec = si->si_interval;
924                 ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, defer );
925                 if ( si->si_retrynum ) {
926                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
927                                 si->si_retrynum[i] = si->si_retrynum_init[i];
928                         }
929                         si->si_retrynum[i] = -2;
930                 }
931         } else {
932                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
933                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
934                                 break;
935                 }
936
937                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
938                         ldap_pvt_runqueue_remove( &syncrepl_rq, rtask );
939                 } else if ( si->si_retrynum[i] >= -1 ) {
940                         if ( si->si_retrynum[i] > 0 )
941                                 si->si_retrynum[i]--;
942                         rtask->interval.tv_sec = si->si_retryinterval[i];
943                         ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, 0 );
944                         slap_wake_listener();
945                 }
946         }
947         
948         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
949
950         return NULL;
951 }
952
953 int
954 syncrepl_message_to_entry(
955         syncinfo_t      *si,
956         Operation       *op,
957         LDAPMessage     *msg,
958         Modifications   **modlist,
959         Entry                   **entry,
960         int             syncstate
961 )
962 {
963         Entry           *e = NULL;
964         BerElement      *ber = NULL;
965         Modifications   tmp;
966         Modifications   *mod;
967         Modifications   **modtail = modlist;
968
969         const char      *text;
970         char txtbuf[SLAP_TEXT_BUFLEN];
971         size_t textlen = sizeof txtbuf;
972
973         struct berval   bdn = {0, NULL}, dn, ndn;
974         int             rc;
975
976         *modlist = NULL;
977
978         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
979 #ifdef NEW_LOGGING
980                 LDAP_LOG( OPERATION, ERR,
981                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
982 #else
983                 Debug( LDAP_DEBUG_ANY,
984                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
985 #endif
986                 return -1;
987         }
988
989         op->o_tag = LDAP_REQ_ADD;
990
991         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
992
993         if ( rc != LDAP_SUCCESS ) {
994 #ifdef NEW_LOGGING
995                 LDAP_LOG( OPERATION, ERR,
996                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
997 #else
998                 Debug( LDAP_DEBUG_ANY,
999                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1000 #endif
1001                 return rc;
1002         }
1003
1004         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1005         ber_dupbv( &op->o_req_dn, &dn );
1006         ber_dupbv( &op->o_req_ndn, &ndn );
1007         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1008         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1009
1010         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1011                 return LDAP_SUCCESS;
1012         }
1013
1014         if ( entry == NULL ) {
1015                 return -1;
1016         }
1017
1018         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1019         *entry = e;
1020         e->e_name = op->o_req_dn;
1021         e->e_nname = op->o_req_ndn;
1022
1023         while ( ber_remaining( ber ) ) {
1024                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1025                         LBER_ERROR ) || ( tmp.sml_type.bv_val == NULL ))
1026                 {
1027                         break;
1028                 }
1029
1030                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1031
1032                 mod->sml_op = LDAP_MOD_REPLACE;
1033                 mod->sml_next = NULL;
1034                 mod->sml_desc = NULL;
1035                 mod->sml_type = tmp.sml_type;
1036                 mod->sml_values = tmp.sml_values;
1037                 mod->sml_nvalues = NULL;
1038
1039                 *modtail = mod;
1040                 modtail = &mod->sml_next;
1041         }
1042
1043         if ( *modlist == NULL ) {
1044 #ifdef NEW_LOGGING
1045                 LDAP_LOG( OPERATION, ERR,
1046                         "syncrepl_message_to_entry: no attributes\n", 0, 0, 0 );
1047 #else
1048                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1049                         0, 0, 0 );
1050 #endif
1051         }
1052
1053         rc = slap_mods_check( *modlist, 1, &text, txtbuf, textlen, NULL );
1054
1055         if ( rc != LDAP_SUCCESS ) {
1056 #ifdef NEW_LOGGING
1057                 LDAP_LOG( OPERATION, ERR,
1058                         "syncrepl_message_to_entry: mods check (%s)\n", text, 0, 0 );
1059 #else
1060                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1061                         text, 0, 0 );
1062 #endif
1063                 goto done;
1064         }
1065
1066         /* Strip out dynamically generated attrs */
1067         for ( modtail = modlist; *modtail ; ) {
1068                 mod = *modtail;
1069                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1070                         *modtail = mod->sml_next;
1071                         slap_mod_free( &mod->sml_mod, 0 );
1072                         free( mod );
1073                 } else {
1074                         modtail = &mod->sml_next;
1075                 }
1076         }
1077         
1078         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1079         if( rc != LDAP_SUCCESS ) {
1080 #ifdef NEW_LOGGING
1081                 LDAP_LOG( OPERATION, ERR,
1082                         "syncrepl_message_to_entry: mods2entry (%s)\n", text, 0, 0 );
1083 #else
1084                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1085                         text, 0, 0 );
1086 #endif
1087         }
1088
1089 done:
1090         ber_free ( ber, 0 );
1091         if ( rc != LDAP_SUCCESS ) {
1092                 entry_free( e );
1093                 *entry = e = NULL;
1094         }
1095
1096         return rc;
1097 }
1098
1099 int
1100 syncrepl_entry(
1101         syncinfo_t* si,
1102         Operation *op,
1103         Entry* e,
1104         Modifications* modlist,
1105         int syncstate,
1106         struct berval* syncUUID,
1107         struct sync_cookie* syncCookie_req )
1108 {
1109         Backend *be = op->o_bd;
1110         slap_callback   cb = { NULL };
1111         struct berval   *syncuuid_bv = NULL;
1112         struct berval   syncUUID_strrep = BER_BVNULL;
1113         struct berval   uuid_bv = BER_BVNULL;
1114
1115         SlapReply       rs_search = {REP_RESULT};
1116         SlapReply       rs_delete = {REP_RESULT};
1117         SlapReply       rs_add = {REP_RESULT};
1118         SlapReply       rs_modify = {REP_RESULT};
1119         Filter f = {0};
1120         AttributeAssertion ava = {0};
1121         int rc = LDAP_SUCCESS;
1122         int ret = LDAP_SUCCESS;
1123         const char *text;
1124
1125         struct berval pdn = BER_BVNULL;
1126         struct berval org_req_dn = BER_BVNULL;
1127         struct berval org_req_ndn = BER_BVNULL;
1128         struct berval org_dn = BER_BVNULL;
1129         struct berval org_ndn = BER_BVNULL;
1130         int     org_managedsait;
1131
1132         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1133                 syncuuid_bv = ber_dupbv( NULL, syncUUID );
1134                 avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1135                         syncuuid_cmp, avl_dup_error );
1136         }
1137
1138         if ( syncstate == LDAP_SYNC_PRESENT ) {
1139                 return e ? 1 : 0;
1140         }
1141
1142         f.f_choice = LDAP_FILTER_EQUALITY;
1143         f.f_ava = &ava;
1144         ava.aa_desc = slap_schema.si_ad_entryUUID;
1145         slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1146         ava.aa_value = *syncUUID;
1147         op->ors_filter = &f;
1148
1149         op->ors_filterstr.bv_len = (sizeof("entryUUID=")-1) + syncUUID->bv_len;
1150         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1151                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1152         AC_MEMCPY( op->ors_filterstr.bv_val, "entryUUID=", sizeof("entryUUID=")-1 );
1153         AC_MEMCPY( &op->ors_filterstr.bv_val[sizeof("entryUUID=")-1],
1154                 syncUUID->bv_val, syncUUID->bv_len );
1155         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1156
1157         op->o_tag = LDAP_REQ_SEARCH;
1158         op->ors_scope = LDAP_SCOPE_SUBTREE;
1159
1160         /* get syncrepl cookie of shadow replica from subentry */
1161         op->o_req_dn = si->si_base;
1162         op->o_req_ndn = si->si_base;
1163
1164         op->o_time = slap_get_time();
1165         op->ors_tlimit = SLAP_NO_LIMIT;
1166         op->ors_slimit = 1;
1167
1168         op->ors_attrs = slap_anlist_no_attrs;
1169         op->ors_attrsonly = 1;
1170
1171         /* set callback function */
1172         op->o_callback = &cb;
1173         cb.sc_response = dn_callback;
1174         cb.sc_private = si;
1175
1176         si->si_syncUUID_ndn.bv_val = NULL;
1177
1178         if ( limits_check( op, &rs_search ) == 0 ) {
1179                 rc = be->be_search( op, &rs_search );
1180         }
1181
1182         if ( op->ors_filterstr.bv_val ) {
1183                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1184         }
1185
1186         cb.sc_response = null_callback;
1187         cb.sc_private = si;
1188
1189         if ( rs_search.sr_err == LDAP_SUCCESS && si->si_syncUUID_ndn.bv_val ) {
1190                 char *subseq_ptr;
1191
1192                 if ( syncstate != LDAP_SYNC_DELETE ) {
1193                         op->o_no_psearch = 1;
1194                 }
1195
1196                 ber_dupbv( &op->o_sync_csn, syncCookie_req->ctxcsn );
1197                 if ( op->o_sync_csn.bv_val ) {
1198                         subseq_ptr = strstr( op->o_sync_csn.bv_val, "#0000" );
1199                         subseq_ptr += 4;
1200                         *subseq_ptr = '1';
1201                 }
1202                 
1203                 op->o_req_dn = si->si_syncUUID_ndn;
1204                 op->o_req_ndn = si->si_syncUUID_ndn;
1205                 op->o_tag = LDAP_REQ_DELETE;
1206                 rc = be->be_delete( op, &rs_delete );
1207
1208                 org_req_dn = op->o_req_dn;
1209                 org_req_ndn = op->o_req_ndn;
1210                 org_dn = op->o_dn;
1211                 org_ndn = op->o_ndn;
1212                 org_managedsait = get_manageDSAit( op );
1213                 op->o_dn = op->o_bd->be_rootdn;
1214                 op->o_ndn = op->o_bd->be_rootndn;
1215                 op->o_managedsait = 1;
1216
1217                 while ( rs_delete.sr_err == LDAP_SUCCESS && op->o_delete_glue_parent ) {
1218                         op->o_delete_glue_parent = 0;
1219                         if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1220                                 slap_callback cb = { NULL };
1221                                 cb.sc_response = slap_null_cb;
1222                                 dnParent( &op->o_req_ndn, &pdn );
1223                                 op->o_req_dn = pdn;
1224                                 op->o_req_ndn = pdn;
1225                                 op->o_callback = &cb;
1226                                 op->o_bd->be_delete( op, &rs_delete );
1227                         } else {
1228                                 break;
1229                     }
1230                 }
1231
1232                 op->o_managedsait = org_managedsait;
1233                 op->o_dn = org_dn;
1234                 op->o_ndn = org_ndn;
1235                 op->o_req_dn = org_req_dn;
1236                 op->o_req_ndn = org_req_ndn;
1237                 op->o_delete_glue_parent = 0;
1238
1239                 op->o_no_psearch = 0;
1240         }
1241
1242         switch ( syncstate ) {
1243         case LDAP_SYNC_ADD:
1244         case LDAP_SYNC_MODIFY:
1245                 if ( rs_search.sr_err == LDAP_SUCCESS ||
1246                          rs_search.sr_err == LDAP_REFERRAL ||
1247                          rs_search.sr_err == LDAP_NO_SUCH_OBJECT ||
1248                          rs_search.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF )
1249                 {
1250                         attr_delete( &e->e_attrs, slap_schema.si_ad_entryUUID );
1251                         attr_merge_one( e, slap_schema.si_ad_entryUUID,
1252                                 &syncUUID_strrep, syncUUID );
1253
1254                         op->o_tag = LDAP_REQ_ADD;
1255                         op->ora_e = e;
1256                         op->o_req_dn = e->e_name;
1257                         op->o_req_ndn = e->e_nname;
1258
1259                         rc = be->be_add( op, &rs_add );
1260
1261                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1262                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS &&
1263                                          rs_search.sr_err != LDAP_NO_SUCH_OBJECT ) {
1264                                         Modifications *mod;
1265                                         Modifications *modtail = modlist;
1266
1267                                         assert( modlist );
1268
1269                                         for ( mod = modlist; mod != NULL; mod = mod->sml_next ) {
1270                                                 modtail = mod;
1271                                         }
1272
1273                                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1274                                         ber_dupbv( &uuid_bv, syncUUID );
1275                                         mod->sml_op = LDAP_MOD_REPLACE;
1276                                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1277                                         mod->sml_type = mod->sml_desc->ad_cname;
1278                                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1279                                         modtail->sml_next = mod;
1280                                         
1281                                         op->o_tag = LDAP_REQ_MODIFY;
1282                                         op->orm_modlist = modlist;
1283                                         op->o_req_dn = e->e_name;
1284                                         op->o_req_ndn = e->e_nname;
1285
1286                                         rc = be->be_modify( op, &rs_modify );
1287                                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1288 #ifdef NEW_LOGGING
1289                                                 LDAP_LOG( OPERATION, ERR,
1290                                                         "syncrepl_entry : be_modify failed (%d)\n",
1291                                                         rs_modify.sr_err, 0, 0 );
1292 #else
1293                                                 Debug( LDAP_DEBUG_ANY,
1294                                                         "syncrepl_entry : be_modify failed (%d)\n",
1295                                                         rs_modify.sr_err, 0, 0 );
1296 #endif
1297                                         }
1298                                         ret = 1;
1299                                         goto done;
1300                                 } else if ( rs_modify.sr_err == LDAP_REFERRAL ||
1301                                                         rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1302                                         syncrepl_add_glue( op, e );
1303                                         ret = 0;
1304                                         goto done;
1305                                 } else {
1306 #ifdef NEW_LOGGING
1307                                         LDAP_LOG( OPERATION, ERR,
1308                                                 "syncrepl_entry : be_add failed (%d)\n",
1309                                                 rs_add.sr_err, 0, 0 );
1310 #else
1311                                         Debug( LDAP_DEBUG_ANY,
1312                                                 "syncrepl_entry : be_add failed (%d)\n",
1313                                                 rs_add.sr_err, 0, 0 );
1314 #endif
1315                                         ret = 1;
1316                                         goto done;
1317                                 }
1318                         } else {
1319                                 be_entry_release_w( op, e );
1320                                 ret = 0;
1321                                 goto done;
1322                         }
1323                 } else {
1324 #ifdef NEW_LOGGING
1325                         LDAP_LOG( OPERATION, ERR,
1326                                 "syncrepl_entry : be_search failed (%d)\n",
1327                                 rs_search.sr_err, 0, 0 );
1328 #else
1329                         Debug( LDAP_DEBUG_ANY,
1330                                 "syncrepl_entry : be_search failed (%d)\n",
1331                                 rs_search.sr_err, 0, 0 );
1332 #endif
1333                         ret = 1;
1334                         goto done;
1335                 }
1336
1337         case LDAP_SYNC_DELETE :
1338                 /* Already deleted */
1339                 ret = 0;
1340                 goto done;
1341
1342         default :
1343 #ifdef NEW_LOGGING
1344                 LDAP_LOG( OPERATION, ERR,
1345                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1346 #else
1347                 Debug( LDAP_DEBUG_ANY,
1348                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1349 #endif
1350                 ret = 1;
1351                 goto done;
1352         }
1353
1354 done :
1355
1356         if ( syncUUID_strrep.bv_val ) {
1357                 ber_memfree_x( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1358         }
1359         if ( si->si_syncUUID_ndn.bv_val ) {
1360                 ber_memfree_x( si->si_syncUUID_ndn.bv_val, op->o_tmpmemctx );
1361         }
1362         return ret;
1363 }
1364
1365 static struct berval gcbva[] = {
1366         BER_BVC("top"),
1367         BER_BVC("glue"),
1368         BER_BVNULL
1369 };
1370
1371 static void
1372 syncrepl_del_nonpresent(
1373         Operation *op,
1374         syncinfo_t *si )
1375 {
1376         Backend* be = op->o_bd;
1377         slap_callback   cb = { NULL };
1378         SlapReply       rs_search = {REP_RESULT};
1379         SlapReply       rs_delete = {REP_RESULT};
1380         SlapReply       rs_modify = {REP_RESULT};
1381         struct nonpresent_entry *np_list, *np_prev;
1382         int rc;
1383         Modifications *ml;
1384         Modifications *mlnext;
1385         Modifications *mod;
1386         Modifications *modlist = NULL;
1387         Modifications **modtail = &modlist;
1388         Attribute       *attr;
1389         AttributeName   an[2];
1390
1391         struct berval pdn = BER_BVNULL;
1392         struct berval org_req_dn = BER_BVNULL;
1393         struct berval org_req_ndn = BER_BVNULL;
1394         struct berval org_dn = BER_BVNULL;
1395         struct berval org_ndn = BER_BVNULL;
1396         int     org_managedsait;
1397
1398         op->o_req_dn = si->si_base;
1399         op->o_req_ndn = si->si_base;
1400
1401         cb.sc_response = nonpresent_callback;
1402         cb.sc_private = si;
1403
1404         op->o_callback = &cb;
1405         op->o_tag = LDAP_REQ_SEARCH;
1406         op->ors_scope = si->si_scope;
1407         op->ors_deref = LDAP_DEREF_NEVER;
1408         op->o_time = slap_get_time();
1409         op->ors_tlimit = SLAP_NO_LIMIT;
1410         op->ors_slimit = SLAP_NO_LIMIT;
1411
1412         memset( &an[0], 0, 2 * sizeof( AttributeName ) );
1413         an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1414         an[0].an_desc = slap_schema.si_ad_entryUUID;
1415         op->ors_attrs = an;
1416
1417         op->ors_attrsonly = 0;
1418         op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
1419         op->ors_filterstr = si->si_filterstr;
1420
1421         op->o_nocaching = 1;
1422         op->o_managedsait = 0;
1423
1424         if ( limits_check( op, &rs_search ) == 0 ) {
1425                 rc = be->be_search( op, &rs_search );
1426         }
1427
1428         op->o_managedsait = 1;
1429         op->o_nocaching = 0;
1430
1431         if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
1432
1433         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
1434                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
1435                 while ( np_list != NULL ) {
1436                         LDAP_LIST_REMOVE( np_list, npe_link );
1437                         np_prev = np_list;
1438                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
1439                         op->o_tag = LDAP_REQ_DELETE;
1440                         op->o_callback = &cb;
1441                         cb.sc_response = null_callback;
1442                         cb.sc_private = si;
1443                         op->o_req_dn = *np_prev->npe_name;
1444                         op->o_req_ndn = *np_prev->npe_nname;
1445                         rc = op->o_bd->be_delete( op, &rs_delete );
1446
1447                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
1448                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1449                                 mod->sml_op = LDAP_MOD_REPLACE;
1450                                 mod->sml_desc = slap_schema.si_ad_objectClass;
1451                                 mod->sml_type = mod->sml_desc->ad_cname;
1452                                 mod->sml_values = &gcbva[0];
1453                                 *modtail = mod;
1454                                 modtail = &mod->sml_next;
1455
1456                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1457                                 mod->sml_op = LDAP_MOD_REPLACE;
1458                                 mod->sml_desc = slap_schema.si_ad_structuralObjectClass;
1459                                 mod->sml_type = mod->sml_desc->ad_cname;
1460                                 mod->sml_values = &gcbva[1];
1461                                 *modtail = mod;
1462                                 modtail = &mod->sml_next;
1463
1464                                 op->o_tag = LDAP_REQ_MODIFY;
1465                                 op->orm_modlist = modlist;
1466
1467                                 rc = be->be_modify( op, &rs_modify );
1468
1469                                 for ( ml = modlist; ml != NULL; ml = mlnext ) {
1470                                         mlnext = ml->sml_next;
1471                                         free( ml );
1472                                 }
1473                         }
1474
1475                         org_req_dn = op->o_req_dn;
1476                         org_req_ndn = op->o_req_ndn;
1477                         org_dn = op->o_dn;
1478                         org_ndn = op->o_ndn;
1479                         org_managedsait = get_manageDSAit( op );
1480                         op->o_dn = op->o_bd->be_rootdn;
1481                         op->o_ndn = op->o_bd->be_rootndn;
1482                         op->o_managedsait = 1;
1483
1484                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
1485                                         op->o_delete_glue_parent ) {
1486                                 op->o_delete_glue_parent = 0;
1487                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1488                                         slap_callback cb = { NULL };
1489                                         cb.sc_response = slap_null_cb;
1490                                         dnParent( &op->o_req_ndn, &pdn );
1491                                         op->o_req_dn = pdn;
1492                                         op->o_req_ndn = pdn;
1493                                         op->o_callback = &cb;
1494                                         /* give it a root privil ? */
1495                                         op->o_bd->be_delete( op, &rs_delete );
1496                                 } else {
1497                                         break;
1498                             }
1499                         }
1500
1501                         op->o_managedsait = org_managedsait;
1502                         op->o_dn = org_dn;
1503                         op->o_ndn = org_ndn;
1504                         op->o_req_dn = org_req_dn;
1505                         op->o_req_ndn = org_req_ndn;
1506                         op->o_delete_glue_parent = 0;
1507
1508                         ber_bvfree( np_prev->npe_name );
1509                         ber_bvfree( np_prev->npe_nname );
1510                         op->o_req_dn.bv_val = NULL;
1511                         op->o_req_ndn.bv_val = NULL;
1512                         ch_free( np_prev );
1513                 }
1514         }
1515
1516         return;
1517 }
1518
1519 void
1520 syncrepl_add_glue(
1521         Operation* op,
1522         Entry *e )
1523 {
1524         Backend *be = op->o_bd;
1525         slap_callback cb = { NULL };
1526         Attribute       *a;
1527         int     rc;
1528         int suffrdns;
1529         int i;
1530         struct berval dn = {0, NULL};
1531         struct berval ndn = {0, NULL};
1532         Entry   *glue;
1533         SlapReply       rs_add = {REP_RESULT};
1534         char    *ptr, *comma;
1535
1536         op->o_tag = LDAP_REQ_ADD;
1537         op->o_callback = &cb;
1538         cb.sc_response = null_callback;
1539         cb.sc_private = NULL;
1540
1541         dn = e->e_name;
1542         ndn = e->e_nname;
1543
1544         /* count RDNs in suffix */
1545         if ( be->be_nsuffix[0].bv_len ) {
1546                 for (i=0, ptr=be->be_nsuffix[0].bv_val; ptr; ptr=strchr( ptr, ',' )) {
1547                         ptr++;
1548                         i++;
1549                 }
1550                 suffrdns = i;
1551         } else {
1552                 /* suffix is "" */
1553                 suffrdns = 0;
1554         }
1555
1556         /* Start with BE suffix */
1557         for ( i = 0, ptr = NULL; i < suffrdns; i++ ) {
1558                 comma = strrchr(dn.bv_val, ',');
1559                 if ( ptr ) *ptr = ',';
1560                 if ( comma ) *comma = '\0';
1561                 ptr = comma;
1562         }
1563         if ( ptr ) {
1564                 *ptr++ = ',';
1565                 dn.bv_len -= ptr - dn.bv_val;
1566                 dn.bv_val = ptr;
1567         }
1568         /* the normalizedDNs are always the same length, no counting
1569          * required.
1570          */
1571         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
1572                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
1573                 ndn.bv_len = be->be_nsuffix[0].bv_len;
1574         }
1575
1576         while ( ndn.bv_val > e->e_nname.bv_val ) {
1577                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
1578                 ber_dupbv( &glue->e_name, &dn );
1579                 ber_dupbv( &glue->e_nname, &ndn );
1580
1581                 a = ch_calloc( 1, sizeof( Attribute ));
1582                 a->a_desc = slap_schema.si_ad_objectClass;
1583
1584                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1585                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
1586                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
1587                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
1588
1589                 a->a_nvals = a->a_vals;
1590
1591                 a->a_next = glue->e_attrs;
1592                 glue->e_attrs = a;
1593
1594                 a = ch_calloc( 1, sizeof( Attribute ));
1595                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1596
1597                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1598                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
1599                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
1600
1601                 a->a_nvals = a->a_vals;
1602
1603                 a->a_next = glue->e_attrs;
1604                 glue->e_attrs = a;
1605
1606                 op->o_req_dn = glue->e_name;
1607                 op->o_req_ndn = glue->e_nname;
1608                 op->ora_e = glue;
1609                 rc = be->be_add ( op, &rs_add );
1610                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
1611                         be_entry_release_w( op, glue );
1612                 } else {
1613                 /* incl. ALREADY EXIST */
1614                         entry_free( glue );
1615                 }
1616
1617                 /* Move to next child */
1618                 for (ptr = dn.bv_val-2; ptr > e->e_name.bv_val && *ptr != ','; ptr--) {
1619                         /* empty */
1620                 }
1621                 if ( ptr == e->e_name.bv_val ) break;
1622                 dn.bv_val = ++ptr;
1623                 dn.bv_len = e->e_name.bv_len - (ptr-e->e_name.bv_val);
1624                 for( ptr = ndn.bv_val-2;
1625                         ptr > e->e_nname.bv_val && *ptr != ',';
1626                         ptr--)
1627                 {
1628                         /* empty */
1629                 }
1630                 ndn.bv_val = ++ptr;
1631                 ndn.bv_len = e->e_nname.bv_len - (ptr-e->e_nname.bv_val);
1632         }
1633
1634         op->o_req_dn = e->e_name;
1635         op->o_req_ndn = e->e_nname;
1636         op->ora_e = e;
1637         rc = be->be_add ( op, &rs_add );
1638         if ( rs_add.sr_err == LDAP_SUCCESS ) {
1639                 be_entry_release_w( op, e );
1640         } else {
1641                 entry_free( e );
1642         }
1643
1644         return;
1645 }
1646
1647 static struct berval ocbva[] = {
1648         BER_BVC("top"),
1649         BER_BVC("subentry"),
1650         BER_BVC("syncConsumerSubentry"),
1651         BER_BVNULL
1652 };
1653
1654 static struct berval cnbva[] = {
1655         BER_BVNULL,
1656         BER_BVNULL
1657 };
1658
1659 static struct berval ssbva[] = {
1660         BER_BVC("{}"),
1661         BER_BVNULL
1662 };
1663
1664 static struct berval scbva[] = {
1665         BER_BVNULL,
1666         BER_BVNULL
1667 };
1668
1669 void
1670 syncrepl_updateCookie(
1671         syncinfo_t *si,
1672         Operation *op,
1673         struct berval *pdn,
1674         struct sync_cookie *syncCookie )
1675 {
1676         Backend *be = op->o_bd;
1677         Modifications *ml;
1678         Modifications *mlnext;
1679         Modifications *mod;
1680         Modifications *modlist = NULL;
1681         Modifications **modtail = &modlist;
1682
1683         const char      *text;
1684         char txtbuf[SLAP_TEXT_BUFLEN];
1685         size_t textlen = sizeof txtbuf;
1686
1687         Entry* e = NULL;
1688         int rc;
1689
1690         char syncrepl_cbuf[sizeof(CN_STR SYNCREPL_STR)];
1691         struct berval slap_syncrepl_dn_bv = BER_BVNULL;
1692         struct berval slap_syncrepl_cn_bv = BER_BVNULL;
1693         
1694         slap_callback cb = { NULL };
1695         SlapReply       rs_add = {REP_RESULT};
1696         SlapReply       rs_modify = {REP_RESULT};
1697
1698         slap_sync_cookie_free( &si->si_syncCookie, 0 );
1699         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
1700
1701         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1702         mod->sml_op = LDAP_MOD_REPLACE;
1703         mod->sml_desc = slap_schema.si_ad_objectClass;
1704         mod->sml_type = mod->sml_desc->ad_cname;
1705         mod->sml_values = ocbva;
1706         *modtail = mod;
1707         modtail = &mod->sml_next;
1708
1709         ber_dupbv( &cnbva[0], (struct berval *) &slap_syncrepl_bvc );
1710         assert( si->si_rid < 1000 );
1711         cnbva[0].bv_len = snprintf( cnbva[0].bv_val,
1712                 slap_syncrepl_bvc.bv_len + 1,
1713                 "syncrepl%ld", si->si_rid );
1714         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1715         mod->sml_op = LDAP_MOD_REPLACE;
1716         mod->sml_desc = slap_schema.si_ad_cn;
1717         mod->sml_type = mod->sml_desc->ad_cname;
1718         mod->sml_values = cnbva;
1719         *modtail = mod;
1720         modtail = &mod->sml_next;
1721
1722         if ( scbva[0].bv_val ) ch_free( scbva[0].bv_val );
1723         ber_dupbv( &scbva[0], &si->si_syncCookie.octet_str[0] );
1724         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1725         mod->sml_op = LDAP_MOD_REPLACE;
1726         mod->sml_desc = slap_schema.si_ad_syncreplCookie;
1727         mod->sml_type = mod->sml_desc->ad_cname;
1728         mod->sml_values = scbva;
1729         *modtail = mod;
1730         modtail = &mod->sml_next;
1731
1732         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1733         mod->sml_op = LDAP_MOD_REPLACE;
1734         mod->sml_desc = slap_schema.si_ad_subtreeSpecification;
1735         mod->sml_type = mod->sml_desc->ad_cname;
1736         mod->sml_values = ssbva;
1737         *modtail = mod;
1738         modtail = &mod->sml_next;
1739
1740         mlnext = mod;
1741
1742         op->o_tag = LDAP_REQ_ADD;
1743         rc = slap_mods_opattrs( op, modlist, modtail,
1744                  &text, txtbuf, textlen );
1745
1746         for ( ml = modlist; ml != NULL; ml = ml->sml_next ) {
1747                 ml->sml_op = LDAP_MOD_REPLACE;
1748         }
1749
1750         if( rc != LDAP_SUCCESS ) {
1751 #ifdef NEW_LOGGING
1752                 LDAP_LOG( OPERATION, ERR,
1753                         "syncrepl_updateCookie: mods opattrs (%s)\n", text, 0, 0 );
1754 #else
1755                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods opattrs (%s)\n",
1756                          text, 0, 0 );
1757 #endif
1758         }
1759
1760         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1761
1762         slap_syncrepl_cn_bv.bv_val = syncrepl_cbuf;
1763         assert( si->si_rid < 1000 );
1764         slap_syncrepl_cn_bv.bv_len = snprintf( slap_syncrepl_cn_bv.bv_val,
1765                 slap_syncrepl_cn_bvc.bv_len + 1,
1766                 "cn=syncrepl%ld", si->si_rid );
1767
1768         build_new_dn( &slap_syncrepl_dn_bv, pdn, &slap_syncrepl_cn_bv,
1769                 op->o_tmpmemctx );
1770         ber_dupbv( &e->e_name, &slap_syncrepl_dn_bv );
1771         ber_dupbv( &e->e_nname, &slap_syncrepl_dn_bv );
1772
1773         if ( slap_syncrepl_dn_bv.bv_val ) {
1774                 slap_sl_free( slap_syncrepl_dn_bv.bv_val, op->o_tmpmemctx );
1775         }
1776
1777         e->e_attrs = NULL;
1778
1779         rc = slap_mods2entry( modlist, &e, 1, 1, &text, txtbuf, textlen );
1780
1781         if( rc != LDAP_SUCCESS ) {
1782 #ifdef NEW_LOGGING
1783                 LDAP_LOG( OPERATION, ERR,
1784                         "syncrepl_updateCookie: mods2entry (%s)\n", text, 0, 0 );
1785 #else
1786                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods2entry (%s)\n",
1787                          text, 0, 0 );
1788 #endif
1789         }
1790
1791         cb.sc_response = null_callback;
1792         cb.sc_private = si;
1793
1794         op->o_callback = &cb;
1795         op->o_req_dn = e->e_name;
1796         op->o_req_ndn = e->e_nname;
1797
1798         /* update persistent cookie */
1799 update_cookie_retry:
1800         op->o_tag = LDAP_REQ_MODIFY;
1801         op->orm_modlist = modlist;
1802         rc = be->be_modify( op, &rs_modify );
1803
1804         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1805                 if ( rs_modify.sr_err == LDAP_REFERRAL ||
1806                          rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1807                         op->o_tag = LDAP_REQ_ADD;
1808                         op->ora_e = e;
1809                         rc = be->be_add( op, &rs_add );
1810                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1811                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS ) {
1812                                         goto update_cookie_retry;
1813                                 } else if ( rs_add.sr_err == LDAP_REFERRAL ||
1814                                                         rs_add.sr_err == LDAP_NO_SUCH_OBJECT ) {
1815 #ifdef NEW_LOGGING
1816                                         LDAP_LOG( OPERATION, ERR,
1817                                                 "cookie will be non-persistent\n",
1818                                                 0, 0, 0 );
1819 #else
1820                                         Debug( LDAP_DEBUG_ANY,
1821                                                 "cookie will be non-persistent\n",
1822                                                 0, 0, 0 );
1823 #endif
1824                                 } else {
1825 #ifdef NEW_LOGGING
1826                                         LDAP_LOG( OPERATION, ERR,
1827                                                 "be_add failed (%d)\n", rs_add.sr_err, 0, 0 );
1828 #else
1829                                         Debug( LDAP_DEBUG_ANY,
1830                                                 "be_add failed (%d)\n", rs_add.sr_err, 0, 0 );
1831 #endif
1832                                 }
1833                         } else {
1834                                 be_entry_release_w( op, e );
1835                                 goto done;
1836                         }
1837                 } else {
1838 #ifdef NEW_LOGGING
1839                         LDAP_LOG( OPERATION, ERR,
1840                                 "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
1841 #else
1842                         Debug( LDAP_DEBUG_ANY,
1843                                 "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
1844 #endif
1845                 }
1846         }
1847
1848         if ( e != NULL ) {
1849                 entry_free( e );
1850         }
1851
1852 done :
1853
1854         if ( cnbva[0].bv_val ) {
1855                 ch_free( cnbva[0].bv_val );
1856                 cnbva[0].bv_val = NULL;
1857         }
1858         if ( scbva[0].bv_val ) {
1859                 ch_free( scbva[0].bv_val );
1860                 scbva[0].bv_val = NULL;
1861         }
1862
1863         if ( mlnext->sml_next ) {
1864                 slap_mods_free( mlnext->sml_next );
1865                 mlnext->sml_next = NULL;
1866         }
1867
1868         for (ml = modlist ; ml != NULL; ml = mlnext ) {
1869                 mlnext = ml->sml_next;
1870                 free( ml );
1871         }
1872
1873         return;
1874 }
1875
1876 int
1877 syncrepl_isupdate( Operation *op )
1878 {
1879         return ( syncrepl_isupdate_dn( op->o_bd, &op->o_ndn ));
1880 }
1881
1882 int
1883 syncrepl_isupdate_dn(
1884         Backend*                be,
1885         struct berval*  ndn )
1886 {
1887         syncinfo_t*     si;
1888         int                     ret = 0;
1889
1890         if ( !LDAP_STAILQ_EMPTY( &be->be_syncinfo )) {
1891                 LDAP_STAILQ_FOREACH( si, &be->be_syncinfo, si_next ) {
1892                         if ( ( ret = dn_match( &si->si_updatedn, ndn ) ) ) {
1893                                 return ret;
1894                         }
1895                 }
1896         }
1897         return 0;
1898 }
1899
1900 static int
1901 dn_callback(
1902         Operation*      op,
1903         SlapReply*      rs )
1904 {
1905         syncinfo_t *si = op->o_callback->sc_private;
1906
1907         if ( rs->sr_type == REP_SEARCH ) {
1908                 if ( si->si_syncUUID_ndn.bv_val != NULL ) {
1909 #ifdef NEW_LOGGING
1910                         LDAP_LOG( OPERATION, ERR,
1911                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1912 #else
1913                         Debug( LDAP_DEBUG_ANY,
1914                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1915 #endif
1916                 } else {
1917                         ber_dupbv_x( &si->si_syncUUID_ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1918                 }
1919         } else if ( rs->sr_type == REP_RESULT ) {
1920                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
1921 #ifdef NEW_LOGGING
1922                         LDAP_LOG( OPERATION, ERR,
1923                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1924 #else
1925                         Debug( LDAP_DEBUG_ANY,
1926                                 "dn_callback : consistency error - entryUUID is not unique\n", 0, 0, 0 );
1927 #endif
1928                 }
1929         }
1930
1931         return LDAP_SUCCESS;
1932 }
1933
1934 static int
1935 nonpresent_callback(
1936         Operation*      op,
1937         SlapReply*      rs )
1938 {
1939         syncinfo_t *si = op->o_callback->sc_private;
1940         Attribute *a;
1941         int count = 0;
1942         struct berval* present_uuid = NULL;
1943         struct nonpresent_entry *np_entry;
1944
1945         if ( rs->sr_type == REP_RESULT ) {
1946                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
1947                 si->si_presentlist = NULL;
1948
1949         } else if ( rs->sr_type == REP_SEARCH ) {
1950                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
1951
1952                 if ( a == NULL ) return 0;
1953
1954                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
1955                         syncuuid_cmp );
1956
1957                 if ( present_uuid == NULL ) {
1958                         np_entry = (struct nonpresent_entry *)
1959                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
1960                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
1961                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
1962                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
1963
1964                 } else {
1965                         avl_delete( &si->si_presentlist,
1966                                         &a->a_nvals[0], syncuuid_cmp );
1967                         ch_free( present_uuid->bv_val );
1968                         ch_free( present_uuid );
1969                 }
1970         }
1971         return LDAP_SUCCESS;
1972 }
1973
1974 static int
1975 null_callback(
1976         Operation*      op,
1977         SlapReply*      rs )
1978 {
1979         if ( rs->sr_err != LDAP_SUCCESS &&
1980                 rs->sr_err != LDAP_REFERRAL &&
1981                 rs->sr_err != LDAP_ALREADY_EXISTS &&
1982                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
1983                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
1984         {
1985 #ifdef NEW_LOGGING
1986                 LDAP_LOG( OPERATION, ERR,
1987                         "null_callback : error code 0x%x\n",
1988                         rs->sr_err, 0, 0 );
1989 #else
1990                 Debug( LDAP_DEBUG_ANY,
1991                         "null_callback : error code 0x%x\n",
1992                         rs->sr_err, 0, 0 );
1993 #endif
1994         }
1995         return LDAP_SUCCESS;
1996 }
1997
1998 Entry *
1999 slap_create_syncrepl_entry(
2000         Backend *be,
2001         struct berval *context_csn,
2002         struct berval *rdn,
2003         struct berval *cn )
2004 {
2005         Entry* e;
2006
2007         struct berval bv;
2008
2009         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
2010
2011         attr_merge( e, slap_schema.si_ad_objectClass, ocbva, NULL );
2012
2013         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
2014                 &ocbva[1], NULL );
2015
2016         attr_merge_one( e, slap_schema.si_ad_cn, cn, NULL );
2017
2018         if ( context_csn ) {
2019                 attr_merge_one( e, slap_schema.si_ad_syncreplCookie,
2020                         context_csn, NULL );
2021         }
2022
2023         bv.bv_val = "{}";
2024         bv.bv_len = sizeof("{}")-1;
2025         attr_merge_one( e, slap_schema.si_ad_subtreeSpecification, &bv, NULL );
2026
2027         build_new_dn( &e->e_name, &be->be_nsuffix[0], rdn, NULL );
2028         ber_dupbv( &e->e_nname, &e->e_name );
2029
2030         return e;
2031 }
2032
2033 struct berval *
2034 slap_uuidstr_from_normalized(
2035         struct berval* uuidstr,
2036         struct berval* normalized,
2037         void *ctx )
2038 {
2039         struct berval *new;
2040         unsigned char nibble;
2041         int i, d = 0;
2042
2043         if ( normalized == NULL ) return NULL;
2044         if ( normalized->bv_len != 16 ) return NULL;
2045
2046         if ( uuidstr ) {
2047                 new = uuidstr;
2048         } else {
2049                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2050         }
2051
2052         new->bv_len = 36;
2053
2054         if (( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx )) == NULL) {
2055                 if ( !uuidstr ) slap_sl_free( new, ctx );
2056                 return NULL;
2057         }
2058
2059         for ( i = 0; i < 16; i++ ) {
2060                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2061                         new->bv_val[(i<<1)+d] = '-';
2062                         d += 1;
2063                 }
2064
2065                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2066                 if ( nibble < 10 ) {
2067                         new->bv_val[(i<<1)+d] = nibble + '0';
2068                 } else {
2069                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2070                 }
2071
2072                 nibble = (normalized->bv_val[i]) & 0xF;
2073                 if ( nibble < 10 ) {
2074                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2075                 } else {
2076                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2077                 }
2078         }
2079
2080         new->bv_val[new->bv_len] = '\0';
2081         return new;
2082 }
2083
2084 static int
2085 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2086 {
2087         const struct berval *uuid1 = v_uuid1;
2088         const struct berval *uuid2 = v_uuid2;
2089         int rc = uuid1->bv_len - uuid2->bv_len;
2090         if ( rc ) return rc;
2091         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2092 }
2093
2094 static void
2095 avl_ber_bvfree( void *bv )
2096 {
2097         if( bv == NULL ) return;
2098         if ( ((struct berval *)bv)->bv_val != NULL ) {
2099                 ch_free( ((struct berval *)bv)->bv_val );
2100         }
2101         ch_free( (char *) bv );
2102 }