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