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