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