]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
Revert to previous behavior:
[openldap] / servers / slapd / syncrepl.c
1 /* $OpenLDAP$ */
2 /*
3  * Replication Engine which uses the LDAP Sync protocol
4  */
5 /* Copyright (c) 2003 by International Business Machines, Inc.
6  *
7  * International Business Machines, Inc. (hereinafter called IBM) grants
8  * permission under its copyrights to use, copy, modify, and distribute this
9  * Software with or without fee, provided that the above copyright notice and
10  * all paragraphs of this notice appear in all copies, and that the name of IBM
11  * not be used in connection with the marketing of any product incorporating
12  * the Software or modifications thereof, without specific, written prior
13  * permission.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
16  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
17  * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
18  * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
19  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
20  * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
21  */
22
23 #include "portable.h"
24
25 #include <stdio.h>
26
27 #include <ac/string.h>
28 #include <ac/socket.h>
29 #include <db.h>
30
31 #include "ldap_pvt.h"
32 #include "lutil.h"
33 #include "slap.h"
34 #include "lutil_ldap.h"
35
36 #include "ldap_rq.h"
37
38 static void
39 syncrepl_del_nonpresent( LDAP *, Operation * );
40
41 /* callback functions */
42 static int cookie_callback( struct slap_op *, struct slap_rep * );
43 static int dn_callback( struct slap_op *, struct slap_rep * );
44 static int nonpresent_callback( struct slap_op *, struct slap_rep * );
45 static int null_callback( struct slap_op *, struct slap_rep * );
46 static int contextcsn_callback( Operation*, SlapReply* );
47
48 static AttributeDescription **sync_descs;
49
50 struct runqueue_s syncrepl_rq;
51
52 void
53 init_syncrepl()
54 {
55         sync_descs = ch_malloc( 4 * sizeof( AttributeDescription * ));
56         sync_descs[0] = slap_schema.si_ad_objectClass;
57         sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
58         sync_descs[2] = slap_schema.si_ad_entryCSN;
59         sync_descs[3] = NULL;
60 }
61
62 int
63 ldap_sync_search(
64         syncinfo_t *si,
65         LDAP *ld,
66         LDAPControl **sctrls,
67         LDAPControl **cctrls,
68         int *msgidp )
69 {
70         BerElement      *ber;
71         int timelimit;
72         ber_int_t id;
73
74         int rc;
75         BerElement      *sync_ber = NULL;
76         struct berval *sync_bvalp = NULL;
77         LDAPControl c[2];
78         LDAPControl **ctrls;
79         int err;
80         struct timeval timeout;
81
82     /* setup LDAP SYNC control */
83     sync_ber = ber_alloc_t( LBER_USE_DER );
84     ber_set_option( sync_ber, LBER_OPT_BER_MEMCTX, NULL );
85
86     if ( si->syncCookie ) {
87         ber_printf( sync_ber, "{eO}", abs(si->type), si->syncCookie );
88     } else {
89         ber_printf( sync_ber, "{e}", abs(si->type) );
90     }
91
92     if ( ber_flatten( sync_ber, &sync_bvalp ) == LBER_ERROR ) {
93         ber_free( sync_ber, 1 );
94         return LBER_ERROR;
95     }
96     ber_free( sync_ber, 1 );
97
98     ctrls = (LDAPControl**) sl_calloc( 3, sizeof(LDAPControl*), NULL );
99
100     c[0].ldctl_oid = LDAP_CONTROL_SYNC;
101     c[0].ldctl_value = (*sync_bvalp);
102     c[0].ldctl_iscritical = si->type < 0;
103     ctrls[0] = &c[0];
104
105     if ( si->authzId ) {
106         c[1].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
107         c[1].ldctl_value.bv_val = si->authzId;
108         c[1].ldctl_value.bv_len = strlen( si->authzId );
109         c[1].ldctl_iscritical = 1;
110         ctrls[1] = &c[1];
111     } else {
112         ctrls[1] = NULL;
113     }
114
115     ctrls[2] = NULL;
116
117     err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
118
119     ber_bvfree( sync_bvalp );
120     ch_free( ctrls );
121
122     if ( err != LDAP_OPT_SUCCESS )
123         fprintf( stderr, "Could not set controls : %d\n", err );
124
125         timeout.tv_sec = si->tlimit > 0 ? si->tlimit : 1;
126
127         rc = ldap_search_ext( ld, si->base, si->scope, si->filterstr,
128                                                   si->attrs, si->attrsonly, sctrls, cctrls,
129                                                   si->tlimit < 0 ? NULL : &timeout,
130                                                   si->slimit, msgidp );
131
132         return rc;
133 }
134
135 void *
136 do_syncrepl(
137         void    *ctx,
138         void    *arg )
139 {
140         struct re_s* rtask = arg;
141         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
142         Backend *be = si->be;
143
144         SlapReply       rs = {REP_RESULT};
145
146         LDAPControl     c[2];
147         LDAPControl     **sctrls = NULL;
148         LDAPControl     **rctrls = NULL;
149         LDAPControl     *rctrlp = NULL;
150         BerElement      *sync_ber = NULL;
151         struct berval   *sync_bvalp = NULL;
152
153         BerElement      *ctrl_ber = NULL;
154         BerElement      *res_ber = NULL;
155
156         LDAP    *ld = NULL;
157         LDAPMessage     *res = NULL;
158         LDAPMessage     *msg = NULL;
159
160         ber_int_t       msgid;
161
162         int             nresponses, nreferences, nextended, npartial;
163         int             nresponses_psearch;
164
165         int             cancel_msgid = -1;
166         char            *retoid = NULL;
167         struct berval   *retdata = NULL;
168
169         int             sync_info_arrived = 0;
170         Entry           *entry = NULL;
171
172         int             syncstate;
173         struct berval   syncUUID = { 0, NULL };
174         struct berval   syncCookie = { 0, NULL };
175         struct berval   syncCookie_req = { 0, NULL };
176
177         int     rc;
178         int     err;
179         ber_len_t       len;
180         int     syncinfo_arrived = 0;
181
182         char **tmp = NULL;
183         AttributeDescription** descs = NULL;
184
185         Connection conn;
186         Operation op = {0};
187         slap_callback   cb;
188
189         void *memctx = NULL;
190         ber_len_t memsiz;
191         
192         int i, j, k, n;
193         int rc_efree;
194
195         struct berval base_bv = { 0, NULL };
196         struct berval pbase = { 0, NULL };
197         struct berval nbase = { 0, NULL };
198         struct berval sub_bv = { 0, NULL };
199         struct berval psubrdn = { 0, NULL };
200         struct berval nsubrdn = { 0, NULL };
201         struct berval psub = { 0, NULL };
202         struct berval nsub = { 0, NULL };
203         char substr[64];
204         Modifications   *modlist = NULL;
205         Modifications   *ml, *mlnext;
206         char *def_filter_str = NULL;
207
208         const char              *text;
209         int                             match;
210
211         struct timeval *tout_p = NULL;
212         struct timeval tout = { 10, 0 };
213
214 #ifdef NEW_LOGGING
215         LDAP_LOG ( OPERATION, DETAIL1, "do_syncrepl\n", 0, 0, 0 );
216 #else
217         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
218 #endif
219
220         if ( si == NULL )
221                 return NULL;
222
223         if ( abs(si->type) != LDAP_SYNC_REFRESH_ONLY &&
224              abs(si->type) != LDAP_SYNC_REFRESH_AND_PERSIST ) {
225                 return NULL;
226         }
227
228         si->sync_mode = LDAP_SYNC_STATE_MODE;
229
230         /* Init connection to master */
231
232         rc = ldap_initialize( &ld, si->provideruri );
233         if ( rc != LDAP_SUCCESS ) {
234 #ifdef NEW_LOGGING
235                 LDAP_LOG( OPERATION, ERR, "do_syncrepl: "
236                         "ldap_initialize failed (%s)\n",
237                         si->provideruri, 0, 0 );
238 #else
239                 Debug( LDAP_DEBUG_ANY, "do_syncrepl: "
240                         "ldap_initialize failed (%s)\n",
241                         si->provideruri, 0, 0 );
242 #endif
243         }
244
245         op.o_protocol = LDAP_VERSION3;
246         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &op.o_protocol );
247
248         /* Bind to master */
249
250         if ( si->tls ) {
251                 rc = ldap_start_tls_s( ld, NULL, NULL );
252                 if( rc != LDAP_SUCCESS ) {
253 #ifdef NEW_LOGGING
254                         LDAP_LOG ( OPERATION, ERR, "do_syncrepl: "
255                                 "%s: ldap_start_tls failed (%d)\n",
256                                 si->tls == TLS_CRITICAL ? "Error" : "Warning",
257                                 rc, 0 );
258 #else
259                         Debug( LDAP_DEBUG_ANY,
260                                 "%s: ldap_start_tls failed (%d)\n",
261                                 si->tls == TLS_CRITICAL ? "Error" : "Warning",
262                                 rc, 0 );
263 #endif
264                         if( si->tls == TLS_CRITICAL )
265                                 return NULL;
266                 }
267         }
268
269         if ( si->bindmethod == LDAP_AUTH_SASL ) {
270 #ifdef HAVE_CYRUS_SASL
271                 void *defaults;
272
273                 if ( si->secprops != NULL ) {
274                         int err = ldap_set_option( ld,
275                                         LDAP_OPT_X_SASL_SECPROPS, si->secprops);
276
277                         if( err != LDAP_OPT_SUCCESS ) {
278 #ifdef NEW_LOGGING
279                                 LDAP_LOG ( OPERATION, ERR, "do_bind: Error: "
280                                         "ldap_set_option(%s,SECPROPS,\"%s\") failed!\n",
281                                         si->provideruri, si->secprops, 0 );
282 #else
283                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
284                                         "(%s,SECPROPS,\"%s\") failed!\n",
285                                         si->provideruri, si->secprops, NULL );
286 #endif
287                                 return NULL;
288                         }
289                 }
290
291                 defaults = lutil_sasl_defaults( ld,
292                                 si->saslmech,
293                                 si->realm,
294                                 si->authcId,
295                                 si->passwd,
296                                 si->authzId );
297
298                 rc = ldap_sasl_interactive_bind_s( ld,
299                                 si->binddn,
300                                 si->saslmech,
301                                 NULL, NULL,
302                                 LDAP_SASL_QUIET,
303                                 lutil_sasl_interact,
304                                 defaults );
305
306                 /* FIXME : different error behaviors according to
307                         1) return code
308                         2) on err policy : exit, retry, backoff ...
309                 */
310                 if ( rc != LDAP_SUCCESS ) {
311 #ifdef NEW_LOGGING
312                         LDAP_LOG ( OPERATION, ERR, "do_syncrepl: "
313                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
314                                 rc, 0, 0 );
315 #else
316                         Debug( LDAP_DEBUG_ANY, "do_syncrepl: "
317                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
318                                 rc, 0, 0 );
319 #endif
320                         return NULL;
321                 }
322 #else /* HAVE_CYRUS_SASL */
323                 fprintf( stderr, "not compiled with SASL support\n" );
324                 return NULL;
325 #endif
326         } else {
327                 rc = ldap_bind_s( ld, si->binddn, si->passwd, si->bindmethod );
328                 if ( rc != LDAP_SUCCESS ) {
329 #ifdef NEW_LOGGING
330                         LDAP_LOG ( OPERATION, ERR, "do_syncrepl: "
331                                 "ldap_bind_s failed (%d)\n", rc, 0, 0 );
332 #else
333                         Debug( LDAP_DEBUG_ANY, "do_syncrepl: "
334                                 "ldap_bind_s failed (%d)\n", rc, 0, 0 );
335 #endif
336                         return NULL;
337                 }
338         }
339
340         /* set thread context in syncinfo */
341         si->ctx = ctx;
342
343         /* set memory context */
344 #define SLAB_SIZE 1048576
345         memsiz = SLAB_SIZE;
346         memctx = sl_mem_create( memsiz, ctx );
347         op.o_tmpmemctx = memctx;
348         op.o_tmpmfuncs = &sl_mfuncs;
349
350         op.o_si = si;
351         op.o_tag = LDAP_REQ_SEARCH;
352         op.o_dn = si->updatedn;
353         op.o_ndn = si->updatedn;
354         op.o_callback = &cb;
355         op.o_time = slap_get_time();
356         op.o_managedsait = 1;
357         op.o_threadctx = si->ctx;
358         op.o_bd = be;
359         op.o_conn = &conn;
360         op.o_connid = op.o_conn->c_connid;
361         op.ors_scope = LDAP_SCOPE_BASE;
362         op.ors_deref = LDAP_DEREF_NEVER;
363         op.ors_slimit = 0;
364         op.ors_tlimit = 0;
365         op.ors_attrsonly = 0;
366         op.ors_attrs = NULL;
367         op.ors_filter = str2filter_x( &op, def_filter_str = "(objectClass=*)" );
368         ber_str2bv( def_filter_str, 0, 0, &op.ors_filterstr );
369
370         si->conn = &conn;
371         conn.c_send_ldap_result = slap_send_ldap_result;
372         conn.c_send_search_entry = slap_send_search_entry;
373         conn.c_send_search_reference = slap_send_search_reference;
374
375         /* get syncrepl cookie of shadow replica from subentry */
376         ber_str2bv( si->base, 0, 0, &base_bv ); 
377         dnPrettyNormal( 0, &base_bv, &pbase, &nbase, op.o_tmpmemctx );
378
379         sprintf( substr, "cn=syncrepl%d", si->id );
380         ber_str2bv( substr, 0, 0, &sub_bv );
381         dnPrettyNormal( 0, &sub_bv, &psubrdn, &nsubrdn, op.o_tmpmemctx );
382
383         build_new_dn( &op.o_req_dn, &pbase, &psubrdn, op.o_tmpmemctx );
384         build_new_dn( &op.o_req_ndn, &nbase, &nsubrdn, op.o_tmpmemctx );
385
386         /* set callback function */
387         cb.sc_response = cookie_callback;
388         cb.sc_private = si;
389
390         /* search subentry to retrieve cookie */
391         si->syncCookie = NULL;
392         be->be_search( &op, &rs );
393
394         ber_dupbv( &syncCookie_req, si->syncCookie );
395
396         psub = be->be_nsuffix[0];
397
398         for ( n = 0; si->attrs[ n ] != NULL; n++ ) ;
399
400         if ( n != 0 ) {
401                 /* Delete Attributes */
402                 descs = sync_descs;
403                 for ( i = 0; descs[i] != NULL; i++ ) {
404                         for ( j = 0; si->attrs[j] != NULL; j++ ) {
405                                 if ( !strcmp( si->attrs[j], descs[i]->ad_cname.bv_val )) {
406                                         ch_free( si->attrs[j] );
407                                         for ( k = j; si->attrs[k] != NULL; k++ ) {
408                                                 si->attrs[k] = si->attrs[k+1];
409                                         }
410                                 }
411                         }
412                 }
413                 for ( n = 0; si->attrs[ n ] != NULL; n++ );
414                 tmp = ( char ** ) ch_realloc( si->attrs, ( n + 4 ) * sizeof( char * ));
415                 if ( tmp == NULL ) {
416 #ifdef NEW_LOGGING
417                         LDAP_LOG( OPERATION, ERR, "out of memory\n", 0,0,0 );
418 #else
419                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0,0,0 );
420 #endif
421                 }
422         } else {
423                 tmp = ( char ** ) ch_realloc( si->attrs, 5 * sizeof( char * ));
424                 if ( tmp == NULL ) {
425 #ifdef NEW_LOGGING
426                         LDAP_LOG( OPERATION, ERR, "out of memory\n", 0,0,0 );
427 #else
428                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0,0,0 );
429 #endif
430                 }
431                 tmp[ n++ ] = ch_strdup( "*" );
432         }
433         
434         descs = sync_descs;
435         si->attrs = tmp;
436
437         /* Add Attributes */
438
439         for ( i = 0; descs[ i ] != NULL; i++ ) {
440                 si->attrs[ n++ ] = ch_strdup ( descs[i]->ad_cname.bv_val );
441                 si->attrs[ n ] = NULL;
442         }
443
444         rc = ldap_sync_search( si, ld, NULL, NULL, &msgid );
445         if( rc != LDAP_SUCCESS ) {
446                 fprintf( stderr, "syncrepl: ldap_search_ext: %s (%d)\n",
447                                                         ldap_err2string( rc ), rc );
448                 return NULL;
449         }
450
451         if ( abs(si->type) == LDAP_SYNC_REFRESH_AND_PERSIST ){
452                 tout_p = &tout;
453         } else {
454                 tout_p = NULL;
455         }
456
457         while (( rc = ldap_result( ld, LDAP_RES_ANY, LDAP_MSG_ONE, tout_p, &res )) >= 0 ) {
458
459                 if ( rc == 0 ) {
460                         if ( slapd_abrupt_shutdown ) {
461                                 break;
462                         } else {
463                                 continue;
464                         }
465                 }
466
467                 for ( msg = ldap_first_message( ld, res );
468                       msg != NULL;
469                       msg = ldap_next_message( ld, msg ) )
470                 {
471                         syncCookie.bv_len = 0; syncCookie.bv_val = NULL;
472                         switch( ldap_msgtype( msg ) ) {
473                         case LDAP_RES_SEARCH_ENTRY:
474                                 entry = syncrepl_message_to_entry( si, ld, &op, msg,
475                                         &modlist, &syncstate, &syncUUID, &syncCookie );
476                                 rc_efree = syncrepl_entry( si, ld, &op, entry, modlist,
477                                                 syncstate, &syncUUID, &syncCookie, !syncinfo_arrived );
478                                 if ( syncCookie.bv_len ) {
479                                         syncrepl_updateCookie( si, ld, &op, &psub, &syncCookie );
480                                 }
481                                 if ( rc_efree )
482                                         entry_free( entry );
483                                 for ( ml = modlist; ml != NULL; ml = mlnext ) {
484                                         mlnext = ml->sml_next;
485                                         ber_memfree( ml );
486                                 }
487                                 break;
488
489                         case LDAP_RES_SEARCH_REFERENCE:
490 #ifdef NEW_LOGGING
491                                 LDAP_LOG( OPERATION, ERR,
492                                         "do_syncrepl : reference received\n", 0, 0, 0 );
493 #else
494                                 Debug( LDAP_DEBUG_ANY,
495                                         "do_syncrepl : reference received\n", 0, 0, 0 );
496 #endif
497                                 break;
498
499                         case LDAP_RES_SEARCH_RESULT:
500                                 ldap_parse_result( ld, msg, &err, NULL, NULL, NULL, &rctrls, 0 );
501                                 if ( rctrls ) {
502                                         rctrlp = *rctrls;
503                                         ctrl_ber = ber_alloc_t( LBER_USE_DER );
504                                         ber_set_option( ctrl_ber, LBER_OPT_BER_MEMCTX, &op.o_tmpmemctx );
505                                         ber_write( ctrl_ber, rctrlp->ldctl_value.bv_val, rctrlp->ldctl_value.bv_len, 0 );
506                                         ber_reset( ctrl_ber, 1 );
507
508                                         ber_scanf( ctrl_ber, "{" /*"}"*/);
509                                         if ( ber_peek_tag( ctrl_ber, &len )
510                                                 == LDAP_SYNC_TAG_COOKIE ) {
511                                                 ber_scanf( ctrl_ber, "o", &syncCookie );
512                                         }
513                                 }
514                                 value_match( &match, slap_schema.si_ad_entryCSN,
515                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
516                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
517                                                         &syncCookie_req, &syncCookie, &text );
518                                 if (si->type == LDAP_SYNC_REFRESH_AND_PERSIST) {
519                                         /* FIXME : different error behaviors according to
520                                                 1) err code : LDAP_BUSY ...
521                                                 2) on err policy : stop service, stop sync, retry
522                                         */
523                                         if ( syncCookie.bv_len && match < 0) {
524                                                 syncrepl_updateCookie( si, ld, &op, &psub, &syncCookie );
525                                         }
526                                         if ( ctrl_ber )
527                                                 ber_free( ctrl_ber, 1 );
528                                         goto done;
529                                 } else {
530                                         /* FIXME : different error behaviors according to
531                                                 1) err code : LDAP_BUSY ...
532                                                 2) on err policy : stop service, stop sync, retry
533                                         */
534                                         if ( syncCookie.bv_len && match < 0 ) {
535                                                 syncrepl_updateCookie( si, ld, &op, &psub, &syncCookie);
536                                         }
537                                         if ( si->sync_mode == LDAP_SYNC_STATE_MODE && match < 0 ) {
538                                                         syncrepl_del_nonpresent( ld, &op );
539                                         }
540                                         if ( ctrl_ber )
541                                                 ber_free( ctrl_ber, 1 );
542                                         goto done;
543                                 }
544                                 break;
545
546                         case LDAP_RES_INTERMEDIATE:
547                                 rc = ldap_parse_intermediate( ld, msg,
548                                         &retoid, &retdata, NULL, 0 );
549                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
550                                         sync_info_arrived = 1;
551                                         res_ber = ber_init( retdata );
552                                         ber_scanf( res_ber, "{e" /*"}"*/, &syncstate );
553
554                                         if ( ber_peek_tag( res_ber, &len )
555                                                                 == LDAP_SYNC_TAG_COOKIE ) {
556                                                 ber_scanf( res_ber, /*"{"*/ "o}", &syncCookie );
557                                         } else {
558                                                 if ( syncstate == LDAP_SYNC_NEW_COOKIE ) {
559 #ifdef NEW_LOGGING
560                                                         LDAP_LOG( OPERATION, ERR,
561                                                                 "do_syncrepl : cookie required\n", 0, 0, 0 );
562 #else
563                                                         Debug( LDAP_DEBUG_ANY,
564                                                                 "do_syncrepl : cookie required\n", 0, 0, 0 );
565 #endif
566                                                 }
567                                         }
568
569                                         value_match( &match, slap_schema.si_ad_entryCSN,
570                                                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
571                                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
572                                                                 &syncCookie_req, &syncCookie, &text );
573
574                                         if ( syncCookie.bv_len && match < 0 ) {
575                                                 syncrepl_updateCookie( si, ld, &op, &psub, &syncCookie);
576                                         }
577
578                                         if ( syncstate == LDAP_SYNC_STATE_MODE_DONE ) {
579                                                 if ( match < 0 ) {
580                                                         syncrepl_del_nonpresent( ld, &op );
581                                                 }
582                                                 si->sync_mode = LDAP_SYNC_LOG_MODE;
583                                         } else if ( syncstate == LDAP_SYNC_LOG_MODE_DONE ) {
584                                                 si->sync_mode = LDAP_SYNC_PERSIST_MODE;
585                                         } else if ( syncstate == LDAP_SYNC_REFRESH_DONE ) {
586                                                 si->sync_mode = LDAP_SYNC_PERSIST_MODE;
587                                         } else if ( syncstate != LDAP_SYNC_NEW_COOKIE ||
588                                                                 syncstate != LDAP_SYNC_LOG_MODE_DONE ) {
589 #ifdef NEW_LOGGING
590                                                 LDAP_LOG( OPERATION, ERR,
591                                                         "do_syncrepl : unknown sync info\n", 0, 0, 0 );
592 #else
593                                                 Debug( LDAP_DEBUG_ANY,
594                                                         "do_syncrepl : unknown sync info\n", 0, 0, 0 );
595 #endif
596                                         }
597
598                                         ldap_memfree( retoid );
599                                         ber_bvfree( retdata );
600                                         ber_free( res_ber, 1 );
601                                         break;
602                                 } else {
603 #ifdef NEW_LOGGING
604                                         LDAP_LOG( OPERATION, ERR,"do_syncrepl :"
605                                                 " unknown intermediate "
606                                                 "response\n", 0, 0, 0 );
607 #else
608                                         Debug( LDAP_DEBUG_ANY, "do_syncrepl : "
609                                                 "unknown intermediate response (%d)\n",
610                                                 rc, 0, 0 );
611 #endif
612                                         ldap_memfree( retoid );
613                                         ber_bvfree( retdata );
614                                         break;
615                                 }
616                                 break;
617                         default:
618 #ifdef NEW_LOGGING
619                                 LDAP_LOG( OPERATION, ERR, "do_syncrepl : "
620                                         "unknown message\n", 0, 0, 0 );
621 #else
622                                 Debug( LDAP_DEBUG_ANY, "do_syncrepl : "
623                                         "unknown message\n", 0, 0, 0 );
624 #endif
625                                 break;
626
627                         }
628                 }
629                 ldap_msgfree( res );
630         }
631
632         if ( rc == -1 ) {
633                 int errno;
634                 const char *errstr;
635
636                 ldap_get_option( ld, LDAP_OPT_ERROR_NUMBER, &errno );
637                 errstr = ldap_err2string( errno );
638                 
639 #ifdef NEW_LOGGING
640                 LDAP_LOG( OPERATION, ERR,
641                         "do_syncrepl : %s\n", errstr, 0, 0 );
642 #else
643                 Debug( LDAP_DEBUG_ANY,
644                         "do_syncrepl : %s\n", errstr, 0, 0 );
645 #endif
646         }
647
648 done:
649         if ( syncCookie.bv_val )
650                 ch_free( syncCookie.bv_val );
651         if ( syncCookie_req.bv_val )
652                 ch_free( syncCookie_req.bv_val );
653         if ( syncUUID.bv_val )
654                 ch_free( syncUUID.bv_val );
655
656         if ( res )
657                 ldap_msgfree( res );
658
659         ldap_unbind( ld );
660
661         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
662         ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
663         if ( si->type == LDAP_SYNC_REFRESH_ONLY ) {
664                 ldap_pvt_runqueue_resched( &syncrepl_rq, rtask );
665         } else {
666                 ldap_pvt_runqueue_remove( &syncrepl_rq, rtask );
667         }
668         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
669
670         return NULL;
671 }
672
673 Entry*
674 syncrepl_message_to_entry(
675         syncinfo_t      *si,
676         LDAP            *ld,
677         Operation       *op,
678         LDAPMessage     *msg,
679         Modifications   **modlist,
680         int             *syncstate,
681         struct berval   *syncUUID,
682         struct berval   *syncCookie
683 )
684 {
685         Entry           *e;
686         BerElement      *ber = NULL;
687         BerElement      *tmpber;
688         struct berval   bv = {0, NULL};
689         Modifications   tmp;
690         Modifications   *mod;
691         Modifications   **modtail = modlist;
692         Backend         *be = op->o_bd;
693
694         const char      *text;
695         char txtbuf[SLAP_TEXT_BUFLEN];
696         size_t textlen = sizeof txtbuf;
697
698         struct berval   **bvals = NULL;
699         char            *dn;
700         struct berval   bdn = {0, NULL};
701         Attribute       *attr;
702         struct berval   empty_bv = { 0, NULL };
703         int             rc;
704         char            *a;
705
706         ber_len_t       len;
707         LDAPControl*    rctrlp;
708         LDAPControl**   rctrls = NULL;
709         BerElement*     ctrl_ber;
710
711         ber_tag_t       tag;
712
713         Modifications *ml = NULL;
714         AttributeDescription** descs;
715         int i;
716
717         *modlist = NULL;
718
719         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
720 #ifdef NEW_LOGGING
721                 LDAP_LOG( OPERATION, ERR,
722                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
723 #else
724                 Debug( LDAP_DEBUG_ANY,
725                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
726 #endif
727                 return NULL;
728         }
729
730         op->o_tag = LDAP_REQ_ADD;
731
732         rc = ldap_get_dn_ber( ld, msg, &ber, &bdn );
733
734         if ( rc != LDAP_SUCCESS ) {
735 #ifdef NEW_LOGGING
736                 LDAP_LOG( OPERATION, ERR,
737                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
738 #else
739                 Debug( LDAP_DEBUG_ANY,
740                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
741 #endif
742                 return NULL;
743         }
744
745         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
746         dnPrettyNormal( NULL, &bdn, &e->e_name, &e->e_nname, NULL );
747
748         e->e_attrs = NULL;
749
750         while ( ber_remaining( ber ) ) {
751                 tag = ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values );
752
753                 if ( tag == LBER_ERROR ) break;
754                 if ( tmp.sml_type.bv_val == NULL ) break;
755
756                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
757
758                 mod->sml_op = LDAP_MOD_REPLACE;
759                 mod->sml_next = NULL;
760                 mod->sml_desc = NULL;
761                 mod->sml_type = tmp.sml_type;
762                 mod->sml_bvalues = tmp.sml_bvalues;
763                 mod->sml_nvalues = NULL;
764
765                 *modtail = mod;
766                 modtail = &mod->sml_next;
767         }
768
769         if ( ber_scanf( ber, "}") == LBER_ERROR ) {
770 #ifdef NEW_LOGGING
771                 LDAP_LOG( OPERATION, ERR,
772                                 "syncrepl_message_to_entry: ber_scanf failed\n", 0, 0, 0 );
773 #else
774                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: ber_scanf failed\n",
775                                 0, 0, 0 );
776 #endif
777                 return NULL;
778         }
779
780         ber_free( ber, 0 );
781         tmpber = ldap_get_message_ber( msg );
782         ber = ber_dup( tmpber );
783
784         ber_scanf( ber, "{xx" );
785
786         rc = ldap_int_get_controls( ber, &rctrls );
787
788         if ( rc != LDAP_SUCCESS ) {
789 #ifdef NEW_LOGGING
790                 LDAP_LOG( OPERATION, ERR,
791                         "syncrepl_message_to_entry : control get failed (%d)", rc, 0, 0 );
792 #else
793                 Debug( LDAP_DEBUG_ANY,
794                         "syncrepl_message_to_entry : control get failed (%d)", rc, 0, 0 );
795 #endif
796                 return NULL;
797         }
798
799         if ( rctrls ) {
800                 rctrlp = *rctrls;
801                 ctrl_ber = ber_alloc_t( LBER_USE_DER );
802                 ber_set_option( ctrl_ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
803                 ber_write( ctrl_ber, rctrlp->ldctl_value.bv_val, rctrlp->ldctl_value.bv_len, 0 );
804                 ber_reset( ctrl_ber, 1 );
805                 ber_scanf( ctrl_ber, "{eo", syncstate, syncUUID );
806                 if ( ber_peek_tag( ctrl_ber, &len ) == LDAP_SYNC_TAG_COOKIE ) {
807                         ber_scanf( ctrl_ber, "o}", syncCookie );
808                 }
809                 ber_free( ctrl_ber, 1 );
810         } else {
811 #ifdef NEW_LOGGING
812                 LDAP_LOG( OPERATION, ERR,"syncrepl_message_to_entry : "
813                         " rctrls absent\n", 0, 0, 0 );
814 #else
815                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry :"
816                         " rctrls absent\n", 0, 0, 0 );
817 #endif
818         }
819
820         if ( *syncstate == LDAP_SYNC_PRESENT ) {
821                 e = NULL;
822                 goto done;
823         } else if ( *syncstate == LDAP_SYNC_DELETE ) {
824                 goto done;
825         }
826
827         if ( *modlist == NULL ) {
828 #ifdef NEW_LOGGING
829                 LDAP_LOG( OPERATION, ERR,
830                                 "syncrepl_message_to_entry: no attributes\n", 0, 0, 0 );
831 #else
832                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
833                                 0, 0, 0 );
834 #endif
835         }
836
837         ml = *modlist;
838         while ( ml != NULL ) {
839                 AttributeDescription *ad = NULL;
840         rc = slap_bv2ad( &ml->sml_type, &ml->sml_desc, &text );
841
842                 if( rc != LDAP_SUCCESS ) {
843                         e = NULL;
844                         goto done;
845                 }
846
847                 ad = ml->sml_desc;
848                 ml->sml_desc = NULL;
849                 ml = ml->sml_next;
850         }
851
852         rc = slap_mods_check( *modlist, 1, &text, txtbuf, textlen, NULL );
853
854         if ( rc != LDAP_SUCCESS ) {
855 #ifdef NEW_LOGGING
856                 LDAP_LOG( OPERATION, ERR,
857                                 "syncrepl_message_to_entry: mods check (%s)\n", text, 0, 0 );
858 #else
859                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
860                                 text, 0, 0 );
861 #endif
862                 return NULL;
863         }
864         
865         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
866         if( rc != LDAP_SUCCESS ) {
867 #ifdef NEW_LOGGING
868                 LDAP_LOG( OPERATION, ERR,
869                                 "syncrepl_message_to_entry: mods2entry (%s)\n", text, 0, 0 );
870 #else
871                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
872                                 text, 0, 0 );
873 #endif
874         }
875
876 done:
877
878         ber_free ( ber, 0 );
879
880         return e;
881 }
882
883 int
884 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
885 {
886         const struct berval *uuid1 = v_uuid1;
887         const struct berval *uuid2 = v_uuid2;
888         int rc = uuid1->bv_len - uuid2->bv_len;
889         if ( rc ) return rc;
890         return ( strcmp( uuid1->bv_val, uuid2->bv_val ) );
891 }
892
893 int
894 syncrepl_entry(
895         syncinfo_t* si,
896         LDAP *ld,
897         Operation *op,
898         Entry* e,
899         Modifications* modlist,
900         int syncstate,
901         struct berval* syncUUID,
902         struct berval* syncCookie,
903         int refresh
904 )
905 {
906         Backend *be = op->o_bd;
907         slap_callback   cb;
908         struct berval   csn_bv = {0, NULL};
909         struct berval   *syncuuid_bv = NULL;
910         char csnbuf[ LDAP_LUTIL_CSNSTR_BUFSIZE ];
911
912         SlapReply       rs = {REP_RESULT};
913         int rc = LDAP_SUCCESS;
914
915         struct berval base_bv = {0, NULL};
916
917         char *filterstr;
918         Filter *filter;
919
920         Attribute *a;
921
922         if ( refresh &&
923                         ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
924                 syncuuid_bv = ber_dupbv( NULL, syncUUID );
925                 avl_insert( &si->presentlist, (caddr_t) syncuuid_bv,
926                                                 syncuuid_cmp, avl_dup_error );
927         }
928
929         if ( syncstate == LDAP_SYNC_PRESENT ) {
930                 if ( e )
931                         return 1;
932                 else
933                         return 0;
934         }
935
936         filterstr = (char *) sl_malloc( strlen("entryUUID=") + syncUUID->bv_len + 1,
937                                                                         op->o_tmpmemctx ); 
938         strcpy( filterstr, "entryUUID=" );
939         strcat( filterstr, syncUUID->bv_val );
940
941         si->e = e;
942         si->syncUUID = syncUUID;
943         si->syncUUID_ndn = NULL;
944
945         filter = str2filter( filterstr );
946         ber_str2bv( filterstr, strlen(filterstr), 1, &op->ors_filterstr );
947         ch_free( filterstr );
948         op->ors_filter = filter;
949         op->ors_scope = LDAP_SCOPE_SUBTREE;
950
951         /* get syncrepl cookie of shadow replica from subentry */
952         ber_str2bv( si->base, strlen(si->base), 1, &base_bv ); 
953         dnPrettyNormal( 0, &base_bv, &op->o_req_dn, &op->o_req_ndn, op->o_tmpmemctx );
954         ch_free( base_bv.bv_val );
955
956         /* set callback function */
957         op->o_callback = &cb;
958         cb.sc_response = dn_callback;
959         cb.sc_private = si;
960
961         si->syncUUID_ndn = NULL;
962
963         rc = be->be_search( op, &rs );
964
965         ch_free( op->o_req_dn.bv_val );
966         ch_free( op->o_req_ndn.bv_val );
967         filter_free( op->ors_filter );
968         ch_free( op->ors_filterstr.bv_val );
969
970         cb.sc_response = null_callback;
971         cb.sc_private = si;
972
973         if ( rc == LDAP_SUCCESS && si->syncUUID_ndn && si->sync_mode != LDAP_SYNC_LOG_MODE ) {
974                 op->o_req_dn = *si->syncUUID_ndn;
975                 op->o_req_ndn = *si->syncUUID_ndn;
976                 op->o_tag = LDAP_REQ_DELETE;
977                 rc = be->be_delete( op, &rs );
978         }
979
980         if ( si->syncUUID_ndn ) {
981                 ber_bvfree( si->syncUUID_ndn );
982         }
983
984         switch ( syncstate ) {
985         case LDAP_SYNC_ADD :
986         case LDAP_SYNC_MODIFY :
987
988                 if ( rc == LDAP_SUCCESS ||
989                          rc == LDAP_REFERRAL ||
990                          rc == LDAP_NO_SUCH_OBJECT ) {
991
992                         attr_delete( &e->e_attrs, slap_schema.si_ad_entryUUID );
993                         attr_merge_normalize_one( e, slap_schema.si_ad_entryUUID, syncUUID, op->o_tmpmemctx );
994
995                         op->o_tag = LDAP_REQ_ADD;
996                         op->ora_e = e;
997                         op->o_req_dn = e->e_name;
998                         op->o_req_ndn = e->e_nname;
999                         rc = be->be_add( op, &rs );
1000
1001                         if ( rc != LDAP_SUCCESS ) {
1002                                 if ( rc == LDAP_ALREADY_EXISTS ) {      
1003                                         op->o_tag = LDAP_REQ_MODIFY;
1004                                         op->orm_modlist = modlist;
1005                                         op->o_req_dn = e->e_name;
1006                                         op->o_req_ndn = e->e_nname;
1007                                         rc = be->be_modify( op, &rs );
1008                                         si->e = NULL;
1009                                         if ( rc != LDAP_SUCCESS ) {
1010 #ifdef NEW_LOGGING
1011                                                 LDAP_LOG( OPERATION, ERR,
1012                                                         "syncrepl_entry : be_modify failed (%d)\n",
1013                                                         rc, 0, 0 );
1014 #else
1015                                                 Debug( LDAP_DEBUG_ANY,
1016                                                         "syncrepl_entry : be_modify failed (%d)\n",
1017                                                         rc, 0, 0 );
1018 #endif
1019                                                 return 1;
1020                                         }
1021                                         return 0;
1022                                 } else if ( rc == LDAP_REFERRAL ||
1023                                                         rc == LDAP_NO_SUCH_OBJECT ) {
1024                                         syncrepl_add_glue( si, ld, op, e,
1025                                                 modlist, syncstate,
1026                                                 syncUUID, syncCookie);
1027                                         si->e = NULL;
1028                                         return 0;
1029                                 } else {
1030 #ifdef NEW_LOGGING
1031                                         LDAP_LOG( OPERATION, ERR,
1032                                                 "syncrepl_entry : be_add failed (%d)\n",
1033                                                 rc, 0, 0 );
1034 #else
1035                                         Debug( LDAP_DEBUG_ANY,
1036                                                 "syncrepl_entry : be_add failed (%d)\n",
1037                                                 rc, 0, 0 );
1038 #endif
1039                                         si->e = NULL;
1040                                         return 1;
1041                                 }
1042                         } else {
1043                                 si->e = NULL;
1044                                 be_entry_release_w( op, e );
1045                                 return 0;
1046                         }
1047                 } else {
1048 #ifdef NEW_LOGGING
1049                         LDAP_LOG( OPERATION, ERR,
1050                                 "syncrepl_entry : be_search failed (%d)\n", rc, 0, 0 );
1051 #else
1052                         Debug( LDAP_DEBUG_ANY,
1053                                 "syncrepl_entry : be_search failed (%d)\n", rc, 0, 0 );
1054 #endif
1055                         si->e = NULL;
1056                         return 1;
1057                 }
1058
1059         case LDAP_SYNC_DELETE :
1060                 if ( si->sync_mode == LDAP_SYNC_LOG_MODE ) {
1061                         op->o_req_dn = *si->syncUUID_ndn;
1062                         op->o_req_ndn = *si->syncUUID_ndn;
1063                         op->o_tag = LDAP_REQ_DELETE;
1064                         rc = be->be_delete( op, &rs );
1065                 }
1066                 /* Already deleted otherwise */
1067                 return 1;
1068
1069         default :
1070 #ifdef NEW_LOGGING
1071                 LDAP_LOG( OPERATION, ERR,
1072                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1073 #else
1074                 Debug( LDAP_DEBUG_ANY,
1075                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1076 #endif
1077                 return 1;
1078         }
1079 }
1080
1081 static void
1082 syncrepl_del_nonpresent(
1083         LDAP *ld,
1084         Operation *op
1085 )
1086 {
1087         Backend* be = op->o_bd;
1088         syncinfo_t *si = op->o_si;
1089         slap_callback   cb;
1090         struct berval   base_bv = {0, NULL};
1091         Filter *filter;
1092         SlapReply       rs = {REP_RESULT};
1093         struct berval   filterstr_bv = {0, NULL};
1094         struct nonpresent_entry *np_list, *np_prev;
1095
1096         ber_str2bv( si->base, strlen(si->base), 1, &base_bv ); 
1097         dnPrettyNormal(0, &base_bv, &op->o_req_dn, &op->o_req_ndn, op->o_tmpmemctx );
1098         ch_free( base_bv.bv_val );
1099
1100         filter = str2filter( si->filterstr );
1101
1102         cb.sc_response = nonpresent_callback;
1103         cb.sc_private = si;
1104
1105         op->o_callback = &cb;
1106         op->o_tag = LDAP_REQ_SEARCH;
1107         op->ors_scope = si->scope;
1108         op->ors_deref = LDAP_DEREF_NEVER;
1109         op->ors_slimit = 0;
1110         op->ors_tlimit = 0;
1111         op->ors_attrsonly = 0;
1112         op->ors_attrs = NULL;
1113         op->ors_filter = filter;
1114         ber_str2bv( si->filterstr, strlen( si->filterstr ), 1, &op->ors_filterstr );
1115
1116         be->be_search( op, &rs );
1117
1118         if ( !LDAP_LIST_EMPTY( &si->nonpresentlist ) ) {
1119                 np_list = LDAP_LIST_FIRST( &si->nonpresentlist );
1120                 while ( np_list != NULL ) {
1121                         LDAP_LIST_REMOVE( np_list, np_link );
1122                         np_prev = np_list;
1123                         np_list = LDAP_LIST_NEXT( np_list, np_link );
1124                         op->o_tag = LDAP_REQ_DELETE;
1125                         op->o_callback = &cb;
1126                         cb.sc_response = null_callback;
1127                         cb.sc_private = si;
1128                         op->o_req_dn = *np_prev->dn;
1129                         op->o_req_ndn = *np_prev->ndn;
1130                         op->o_bd->be_delete( op, &rs );
1131                         ber_bvfree( np_prev->dn );
1132                         ber_bvfree( np_prev->ndn );
1133                         op->o_req_dn.bv_val = NULL;
1134                         op->o_req_ndn.bv_val = NULL;
1135                         ch_free( np_prev );
1136                 }
1137         }
1138
1139         if ( op->o_req_dn.bv_val )
1140                 ch_free( op->o_req_dn.bv_val );
1141         if ( op->o_req_ndn.bv_val )
1142                 ch_free( op->o_req_ndn.bv_val );
1143         filter_free( op->ors_filter );
1144         ch_free( op->ors_filterstr.bv_val );
1145
1146         return;
1147 }
1148
1149
1150 void
1151 syncrepl_add_glue(
1152         syncinfo_t *si,
1153         LDAP *ld,
1154         Operation* op,
1155         Entry *e,
1156         Modifications* modlist,
1157         int syncstate,
1158         struct berval* syncUUID,
1159         struct berval* syncCookie
1160 )
1161 {
1162         Backend *be = op->o_bd;
1163         struct berval   uuid_bv = {0, NULL};
1164         slap_callback cb;
1165         Attribute       *a;
1166         int     rc;
1167         char    uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1168         int levels = 0;
1169         int i, j, k;
1170         struct berval dn = {0, NULL};
1171         struct berval pdn = {0, NULL};
1172         struct berval ndn = {0, NULL};
1173         struct berval rdn = {0, NULL};
1174         Entry   *glue;
1175         SlapReply       rs = {REP_RESULT};
1176         Connection *conn = op->o_conn;
1177         char* ptr;
1178
1179         op->o_tag = LDAP_REQ_ADD;
1180         op->o_callback = &cb;
1181         cb.sc_response = null_callback;
1182         cb.sc_private = si;
1183
1184         ber_dupbv( &dn, &e->e_nname );
1185         ber_dupbv( &pdn, &e->e_nname );
1186
1187         ptr = dn.bv_val;
1188         while ( !be_issuffix ( be, &pdn )) {
1189                 dnParent( &dn, &pdn );
1190                 dn.bv_val = pdn.bv_val;
1191                 dn.bv_len = pdn.bv_len;
1192                 levels++;
1193         }
1194         ch_free( ptr );
1195
1196         for ( i = 0; i <= levels; i++ ) {
1197                 glue = (Entry*) ch_calloc( 1, sizeof(Entry) );
1198                 ber_dupbv( &dn, &e->e_nname );
1199                 j = levels - i;
1200
1201                 ptr = dn.bv_val;
1202                 for ( k = 0; k < j; k++ ) {
1203                         dnParent( &dn, &pdn );
1204                         dn.bv_val = pdn.bv_val;
1205                         dn.bv_len = pdn.bv_len;
1206                 }
1207
1208                 dnPrettyNormal( 0, &dn, &pdn, &ndn, op->o_tmpmemctx );
1209                 ber_dupbv( &glue->e_name, &pdn );
1210                 ber_dupbv( &glue->e_nname, &ndn );
1211                 ch_free( ptr );
1212                 ch_free( pdn.bv_val );
1213                 ch_free( ndn.bv_val );
1214
1215                 a = ch_calloc( 1, sizeof( Attribute ));
1216                 a->a_desc = slap_schema.si_ad_objectClass;
1217
1218                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1219                 ber_str2bv( "top", strlen("top"), 1, &a->a_vals[0] );
1220                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_vals[1] );
1221                 a->a_vals[2].bv_len = 0;
1222                 a->a_vals[2].bv_val = NULL;
1223
1224                 a->a_nvals = ch_calloc( 3, sizeof( struct berval ));
1225                 ber_str2bv( "top", strlen("top"), 1, &a->a_nvals[0] );
1226                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_nvals[1] );
1227                 a->a_nvals[2].bv_len = 0;
1228                 a->a_nvals[2].bv_val = NULL;
1229
1230                 a->a_next = glue->e_attrs;
1231                 glue->e_attrs = a;
1232
1233                 a = ch_calloc( 1, sizeof( Attribute ));
1234                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1235
1236                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1237                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_vals[0] );
1238                 a->a_vals[1].bv_len = 0;
1239                 a->a_vals[1].bv_val = NULL;
1240
1241                 a->a_nvals = ch_calloc( 2, sizeof( struct berval ));
1242                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_nvals[0] );
1243                 a->a_nvals[1].bv_len = 0;
1244                 a->a_nvals[1].bv_val = NULL;
1245
1246                 a->a_next = glue->e_attrs;
1247                 glue->e_attrs = a;
1248
1249                 if ( !strcmp( e->e_nname.bv_val, glue->e_nname.bv_val )) {
1250                         op->o_req_dn = e->e_name;
1251                         op->o_req_ndn = e->e_nname;
1252                         op->ora_e = e;
1253                         rc = be->be_add ( op, &rs );
1254                         if ( rc == LDAP_SUCCESS )
1255                                 be_entry_release_w( op, e );
1256                         else 
1257                                 entry_free( e );
1258                         entry_free( glue );
1259                 } else {
1260                         op->o_req_dn = glue->e_name;
1261                         op->o_req_ndn = glue->e_nname;
1262                         op->ora_e = glue;
1263                         rc = be->be_add ( op, &rs );
1264                         if ( rc == LDAP_SUCCESS ) {
1265                                 be_entry_release_w( op, glue );
1266                         } else {
1267                         /* incl. ALREADY EXIST */
1268                                 entry_free( glue );
1269                         }
1270                 }
1271         }
1272
1273         return;
1274 }
1275
1276 void
1277 syncrepl_updateCookie(
1278         syncinfo_t *si,
1279         LDAP *ld,
1280         Operation *op,
1281         struct berval *pdn,
1282         struct berval *syncCookie
1283 )
1284 {
1285         Backend *be = op->o_bd;
1286         Modifications *ml;
1287         Modifications *mlnext;
1288         Modifications *mod;
1289         Modifications *modlist;
1290         Modifications **modtail = &modlist;
1291
1292         struct berval* ocbva = NULL;
1293         struct berval* cnbva = NULL;
1294         struct berval* ssbva = NULL;
1295         struct berval* scbva = NULL;
1296
1297         char substr[64];
1298         char rdnstr[67];
1299         const char      *text;
1300         char txtbuf[SLAP_TEXT_BUFLEN];
1301         size_t textlen = sizeof txtbuf;
1302
1303         Entry* e;
1304         int rc;
1305
1306         struct berval sub_bv = { 0, NULL };
1307         struct berval psubrdn = { 0, NULL };
1308         
1309         slap_callback cb;
1310         SlapReply       rs = {REP_RESULT};
1311
1312         ocbva = ( struct berval * ) ch_calloc( 4, sizeof( struct berval ));
1313         cnbva = ( struct berval * ) ch_calloc( 2, sizeof( struct berval ));
1314         ssbva = ( struct berval * ) ch_calloc( 2, sizeof( struct berval ));
1315         scbva = ( struct berval * ) ch_calloc( 2, sizeof( struct berval ));
1316
1317         /* update in memory cookie */
1318         if ( si->syncCookie != NULL ) {
1319                 ber_bvfree( si->syncCookie );
1320         }
1321         si->syncCookie = ber_dupbv( NULL, syncCookie );
1322         ber_str2bv( "top", strlen("top"), 1, &ocbva[0] );
1323         ber_str2bv( "subentry", strlen("subentry"), 1, &ocbva[1] );
1324         ber_str2bv( "syncConsumerSubentry",
1325                         strlen("syncConsumerSubentry"), 1, &ocbva[2] );
1326         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1327         mod->sml_op = LDAP_MOD_REPLACE;
1328         ber_str2bv( "objectClass", strlen("objectClass"), 1, &mod->sml_type );
1329         mod->sml_bvalues = ocbva;
1330         *modtail = mod;
1331         modtail = &mod->sml_next;
1332
1333         sprintf( substr, "syncrepl%d", si->id );
1334         sprintf( rdnstr, "cn=%s", substr );
1335         ber_str2bv( substr, strlen( substr ), 1, &cnbva[0] );
1336         ber_str2bv( rdnstr, strlen( rdnstr ), 1, &psubrdn );
1337         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1338         mod->sml_op = LDAP_MOD_REPLACE;
1339         ber_str2bv( "cn", strlen("cn"), 1, &mod->sml_type );
1340         mod->sml_bvalues = cnbva;
1341         *modtail = mod;
1342         modtail = &mod->sml_next;
1343
1344         ber_dupbv( &scbva[0], si->syncCookie );
1345         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1346         mod->sml_op = LDAP_MOD_REPLACE;
1347         ber_str2bv( "syncreplCookie", strlen("syncreplCookie"),
1348                                                 1, &mod->sml_type );
1349         mod->sml_bvalues = scbva;
1350         *modtail = mod;
1351         modtail = &mod->sml_next;
1352
1353         ber_str2bv( "{}", strlen("{}"), 1, &ssbva[0] );
1354         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1355         mod->sml_op = LDAP_MOD_REPLACE;
1356         ber_str2bv( "subtreeSpecification",
1357                         strlen("subtreeSpecification"), 1, &mod->sml_type );
1358         mod->sml_bvalues = ssbva;
1359         *modtail = mod;
1360         modtail = &mod->sml_next;
1361
1362         rc = slap_mods_check( modlist, 1, &text, txtbuf, textlen, NULL );
1363
1364         if ( rc != LDAP_SUCCESS ) {
1365 #ifdef NEW_LOGGING
1366                 LDAP_LOG( OPERATION, ERR,
1367                                 "syncrepl_updateCookie: mods check (%s)\n", text, 0, 0 );
1368 #else
1369                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods check (%s)\n",
1370                          text, 0, 0 );
1371 #endif
1372         }
1373
1374         op->o_tag = LDAP_REQ_ADD;
1375         rc = slap_mods_opattrs( op, modlist, modtail,
1376                                                          &text,txtbuf, textlen );
1377
1378         for ( ml = modlist; ml != NULL; ml = mlnext ) {
1379                 mlnext = ml->sml_next;
1380                 ml->sml_op = LDAP_MOD_REPLACE;
1381         }
1382
1383         if( rc != LDAP_SUCCESS ) {
1384 #ifdef NEW_LOGGING
1385                 LDAP_LOG( OPERATION, ERR,
1386                                 "syncrepl_updateCookie: mods opattrs (%s)\n", text, 0, 0 );
1387 #else
1388                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods opattrs (%s)\n",
1389                          text, 0, 0 );
1390 #endif
1391         }
1392
1393         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1394
1395         build_new_dn( &sub_bv, pdn, &psubrdn, NULL );
1396         dnPrettyNormal( NULL, &sub_bv, &e->e_name, &e->e_nname, NULL );
1397         ch_free( sub_bv.bv_val );
1398         ch_free( psubrdn.bv_val );
1399
1400         e->e_attrs = NULL;
1401
1402         rc = slap_mods2entry( modlist, &e, 1, 1, &text, txtbuf, textlen );
1403
1404         if( rc != LDAP_SUCCESS ) {
1405 #ifdef NEW_LOGGING
1406                 LDAP_LOG( OPERATION, ERR,
1407                                 "syncrepl_updateCookie: mods2entry (%s)\n", text, 0, 0 );
1408 #else
1409                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods2entry (%s)\n",
1410                          text, 0, 0 );
1411 #endif
1412         }
1413
1414         cb.sc_response = null_callback;
1415         cb.sc_private = si;
1416
1417         op->o_callback = &cb;
1418         op->o_req_dn = e->e_name;
1419         op->o_req_ndn = e->e_nname;
1420
1421         /* update persistent cookie */
1422 update_cookie_retry:
1423         op->o_tag = LDAP_REQ_MODIFY;
1424         op->orm_modlist = modlist;
1425         rc = be->be_modify( op, &rs );
1426
1427         if ( rc != LDAP_SUCCESS ) {
1428                 if ( rc == LDAP_REFERRAL ||
1429                          rc == LDAP_NO_SUCH_OBJECT ) {
1430                         op->o_tag = LDAP_REQ_ADD;
1431                         op->ora_e = e;
1432                         rc = be->be_add( op, &rs );
1433                         if ( rc != LDAP_SUCCESS ) {
1434                                 if ( rc == LDAP_ALREADY_EXISTS ) {
1435                                         goto update_cookie_retry;
1436                                 } else if ( rc == LDAP_REFERRAL ||
1437                                                         rc == LDAP_NO_SUCH_OBJECT ) {
1438 #ifdef NEW_LOGGING
1439                                         LDAP_LOG( OPERATION, ERR,
1440                                                 "cookie will be non-persistent\n",
1441                                                 0, 0, 0 );
1442 #else
1443                                         Debug( LDAP_DEBUG_ANY,
1444                                                 "cookie will be non-persistent\n",
1445                                                 0, 0, 0 );
1446 #endif
1447                                 } else {
1448 #ifdef NEW_LOGGING
1449                                         LDAP_LOG( OPERATION, ERR,
1450                                                 "be_add failed (%d)\n",
1451                                                 rc, 0, 0 );
1452 #else
1453                                         Debug( LDAP_DEBUG_ANY,
1454                                                 "be_add failed (%d)\n",
1455                                                 rc, 0, 0 );
1456 #endif
1457                                 }
1458                         } else {
1459                                 be_entry_release_w( op, e );
1460                                 goto done;
1461                         }
1462                 } else {
1463 #ifdef NEW_LOGGING
1464                         LDAP_LOG( OPERATION, ERR,
1465                                 "be_modify failed (%d)\n", rc, 0, 0 );
1466 #else
1467                         Debug( LDAP_DEBUG_ANY,
1468                                 "be_modify failed (%d)\n", rc, 0, 0 );
1469 #endif
1470                 }
1471         }
1472
1473         if ( e != NULL )
1474                 entry_free( e );
1475
1476 done :
1477
1478         for ( ml = modlist; ml != NULL; ml = mlnext ) {
1479                 mlnext = ml->sml_next;
1480                 free( ml );
1481         }
1482
1483         return;
1484 }
1485
1486 void
1487 avl_ber_bvfree( void *bv )
1488 {
1489         if( bv == NULL ) {
1490                 return;
1491         }
1492         if ( ((struct berval *)bv)->bv_val != NULL ) {
1493                 ber_memfree ( ((struct berval *)bv)->bv_val );
1494         }
1495         ber_memfree ( (char *) bv );
1496 }
1497
1498 static int
1499 cookie_callback(
1500         Operation* op,
1501         SlapReply* rs
1502 )
1503 {
1504         syncinfo_t *si = op->o_callback->sc_private;
1505         Attribute *a;
1506
1507         if ( rs->sr_type != REP_SEARCH ) return LDAP_SUCCESS;
1508
1509         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_syncreplCookie );
1510
1511         if ( a == NULL ) {
1512                 si->syncCookie = NULL;
1513         } else {
1514                 si->syncCookie = ber_dupbv( NULL, &a->a_vals[0] );
1515         }
1516         return LDAP_SUCCESS;
1517 }
1518
1519 static int
1520 dn_callback(
1521         Operation*      op,
1522         SlapReply*      rs
1523 )
1524 {
1525         syncinfo_t *si = op->o_callback->sc_private;
1526
1527         if ( rs->sr_type == REP_SEARCH ) {
1528                 if ( si->syncUUID_ndn != NULL ) {
1529 #ifdef NEW_LOGGING
1530                         LDAP_LOG( OPERATION, ERR,
1531                                 "dn_callback : multiple entries match dn\n", 0, 0, 0 );
1532 #else
1533                         Debug( LDAP_DEBUG_ANY,
1534                                 "dn_callback : multiple entries match dn\n", 0, 0, 0 );
1535 #endif
1536                 } else {
1537                         if ( rs->sr_entry == NULL ) {
1538                                 si->syncUUID_ndn = NULL;
1539                         } else {
1540                                 si->syncUUID_ndn = ber_dupbv( NULL, &rs->sr_entry->e_nname );
1541                         }
1542                 }
1543         }
1544
1545         return LDAP_SUCCESS;
1546 }
1547
1548 static int
1549 nonpresent_callback(
1550         Operation*      op,
1551         SlapReply*      rs
1552 )
1553 {
1554         syncinfo_t *si = op->o_callback->sc_private;
1555         Attribute *a;
1556         int count = 0;
1557         struct berval* present_uuid = NULL;
1558         slap_callback cb;
1559         SlapReply       rs_cb = {REP_RESULT};
1560         struct nonpresent_entry *np_entry;
1561
1562         if ( rs->sr_type == REP_RESULT ) {
1563                 count = avl_free( si->presentlist, avl_ber_bvfree );
1564                 si->presentlist = NULL;
1565                 return LDAP_SUCCESS;
1566         } else if ( rs->sr_type == REP_SEARCH ) {
1567                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
1568
1569                 if ( a == NULL )
1570                         return 0;
1571
1572                 present_uuid = avl_find( si->presentlist, &a->a_vals[0], syncuuid_cmp );
1573
1574                 if ( present_uuid == NULL ) {
1575                         np_entry = (struct nonpresent_entry *)
1576                                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
1577                         np_entry->dn = ber_dupbv( NULL, &rs->sr_entry->e_name );
1578                         np_entry->ndn = ber_dupbv( NULL, &rs->sr_entry->e_nname );
1579                         LDAP_LIST_INSERT_HEAD( &si->nonpresentlist, np_entry, np_link );
1580                 } else {
1581                         avl_delete( &si->presentlist,
1582                                         &a->a_vals[0], syncuuid_cmp );
1583                 }
1584                 return LDAP_SUCCESS;
1585         } else {
1586                 return LDAP_SUCCESS;
1587         }
1588
1589 }
1590
1591 static int
1592 null_callback(
1593         Operation*      op,
1594         SlapReply*      rs
1595 )
1596 {
1597         syncinfo_t *si = op->o_callback->sc_private;
1598
1599         if ( rs->sr_err != LDAP_SUCCESS &&
1600                  rs->sr_err != LDAP_REFERRAL &&
1601                  rs->sr_err != LDAP_ALREADY_EXISTS &&
1602                  rs->sr_err != LDAP_NO_SUCH_OBJECT ) {
1603 #ifdef NEW_LOGGING
1604                 LDAP_LOG( OPERATION, ERR,
1605                         "null_callback : error code 0x%x\n",
1606                         rs->sr_err, 0, 0 );
1607 #else
1608                 Debug( LDAP_DEBUG_ANY,
1609                         "null_callback : error code 0x%x\n",
1610                         rs->sr_err, 0, 0 );
1611 #endif
1612         }
1613         return LDAP_SUCCESS;
1614 }
1615
1616
1617 char **
1618 str2clist( char ***out, char *in, const char *brkstr )
1619 {
1620         char    *str;
1621         char    *s;
1622         char    *lasts;
1623         int     i, j;
1624         const char *text;
1625         char    **new;
1626
1627         /* find last element in list */
1628         for (i = 0; *out && *out[i]; i++);
1629
1630         /* protect the input string from strtok */
1631         str = ch_strdup( in );
1632
1633         if ( *str == '\0' ) {
1634                 free( str );
1635                 return( *out );
1636         }
1637
1638         /* Count words in string */
1639         j=1;
1640         for ( s = str; *s; s++ ) {
1641                 if ( strchr( brkstr, *s ) != NULL ) {
1642                         j++;
1643                 }
1644         }
1645
1646         *out = ch_realloc( *out, ( i + j + 1 ) * sizeof( char * ) );
1647         new = *out + i;
1648         for ( s = ldap_pvt_strtok( str, brkstr, &lasts );
1649                 s != NULL;
1650                 s = ldap_pvt_strtok( NULL, brkstr, &lasts ) )
1651         {
1652                 *new = ch_strdup( s );
1653                 new++;
1654         }
1655
1656         *new = NULL;
1657         free( str );
1658         return( *out );
1659 }