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