]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
loose ends fixed
[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 ( modlist ) {
482                                         slap_mods_free( modlist );
483                                 }
484                                 if ( rc_efree ) {
485                                         entry_free( entry );
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                         if ( syncCookie.bv_val )
629                                 ch_free( syncCookie.bv_val );
630                         if ( syncUUID.bv_val )
631                                 ch_free( syncUUID.bv_val );
632                 }
633                 ldap_msgfree( res );
634         }
635
636         if ( rc == -1 ) {
637                 int errno;
638                 const char *errstr;
639
640                 ldap_get_option( ld, LDAP_OPT_ERROR_NUMBER, &errno );
641                 errstr = ldap_err2string( errno );
642                 
643 #ifdef NEW_LOGGING
644                 LDAP_LOG( OPERATION, ERR,
645                         "do_syncrepl : %s\n", errstr, 0, 0 );
646 #else
647                 Debug( LDAP_DEBUG_ANY,
648                         "do_syncrepl : %s\n", errstr, 0, 0 );
649 #endif
650         }
651
652 done:
653         if ( syncCookie.bv_val )
654                 ch_free( syncCookie.bv_val );
655         if ( syncCookie_req.bv_val )
656                 ch_free( syncCookie_req.bv_val );
657         if ( syncUUID.bv_val )
658                 ch_free( syncUUID.bv_val );
659
660         if ( res )
661                 ldap_msgfree( res );
662
663         ldap_unbind( ld );
664
665         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
666         ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
667         if ( si->type == LDAP_SYNC_REFRESH_ONLY ) {
668                 ldap_pvt_runqueue_resched( &syncrepl_rq, rtask );
669         } else {
670                 ldap_pvt_runqueue_remove( &syncrepl_rq, rtask );
671         }
672         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
673
674         return NULL;
675 }
676
677 Entry*
678 syncrepl_message_to_entry(
679         syncinfo_t      *si,
680         LDAP            *ld,
681         Operation       *op,
682         LDAPMessage     *msg,
683         Modifications   **modlist,
684         int             *syncstate,
685         struct berval   *syncUUID,
686         struct berval   *syncCookie
687 )
688 {
689         Entry           *e;
690         BerElement      *ber = NULL;
691         BerElement      *tmpber;
692         struct berval   bv = {0, NULL};
693         Modifications   tmp;
694         Modifications   *mod;
695         Modifications   **modtail = modlist;
696         Backend         *be = op->o_bd;
697
698         const char      *text;
699         char txtbuf[SLAP_TEXT_BUFLEN];
700         size_t textlen = sizeof txtbuf;
701
702         struct berval   **bvals = NULL;
703         char            *dn;
704         struct berval   bdn = {0, NULL};
705         Attribute       *attr;
706         struct berval   empty_bv = { 0, NULL };
707         int             rc;
708         char            *a;
709
710         ber_len_t       len;
711         LDAPControl*    rctrlp;
712         LDAPControl**   rctrls = NULL;
713         BerElement*     ctrl_ber;
714
715         ber_tag_t       tag;
716
717         Modifications *ml = NULL;
718         AttributeDescription** descs;
719         int i;
720
721         *modlist = NULL;
722
723         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
724 #ifdef NEW_LOGGING
725                 LDAP_LOG( OPERATION, ERR,
726                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
727 #else
728                 Debug( LDAP_DEBUG_ANY,
729                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
730 #endif
731                 return NULL;
732         }
733
734         op->o_tag = LDAP_REQ_ADD;
735
736         rc = ldap_get_dn_ber( ld, msg, &ber, &bdn );
737
738         if ( rc != LDAP_SUCCESS ) {
739 #ifdef NEW_LOGGING
740                 LDAP_LOG( OPERATION, ERR,
741                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
742 #else
743                 Debug( LDAP_DEBUG_ANY,
744                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
745 #endif
746                 return NULL;
747         }
748
749         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
750         dnPrettyNormal( NULL, &bdn, &e->e_name, &e->e_nname, NULL );
751
752         e->e_attrs = NULL;
753
754         while ( ber_remaining( ber ) ) {
755                 tag = ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values );
756
757                 if ( tag == LBER_ERROR ) break;
758                 if ( tmp.sml_type.bv_val == NULL ) break;
759
760                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
761
762                 mod->sml_op = LDAP_MOD_REPLACE;
763                 mod->sml_next = NULL;
764                 mod->sml_desc = NULL;
765                 mod->sml_type = tmp.sml_type;
766                 mod->sml_bvalues = tmp.sml_bvalues;
767                 mod->sml_nvalues = NULL;
768
769                 *modtail = mod;
770                 modtail = &mod->sml_next;
771         }
772
773         if ( ber_scanf( ber, "}") == LBER_ERROR ) {
774 #ifdef NEW_LOGGING
775                 LDAP_LOG( OPERATION, ERR,
776                                 "syncrepl_message_to_entry: ber_scanf failed\n", 0, 0, 0 );
777 #else
778                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: ber_scanf failed\n",
779                                 0, 0, 0 );
780 #endif
781                 return NULL;
782         }
783
784         ber_free( ber, 0 );
785         tmpber = ldap_get_message_ber( msg );
786         ber = ber_dup( tmpber );
787
788         ber_scanf( ber, "{xx" );
789
790         rc = ldap_int_get_controls( ber, &rctrls );
791
792         if ( rc != LDAP_SUCCESS ) {
793 #ifdef NEW_LOGGING
794                 LDAP_LOG( OPERATION, ERR,
795                         "syncrepl_message_to_entry : control get failed (%d)", rc, 0, 0 );
796 #else
797                 Debug( LDAP_DEBUG_ANY,
798                         "syncrepl_message_to_entry : control get failed (%d)", rc, 0, 0 );
799 #endif
800                 return NULL;
801         }
802
803         if ( rctrls ) {
804                 rctrlp = *rctrls;
805                 ctrl_ber = ber_alloc_t( LBER_USE_DER );
806                 ber_set_option( ctrl_ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
807                 ber_write( ctrl_ber, rctrlp->ldctl_value.bv_val, rctrlp->ldctl_value.bv_len, 0 );
808                 ber_reset( ctrl_ber, 1 );
809                 ber_scanf( ctrl_ber, "{eo", syncstate, syncUUID );
810                 if ( ber_peek_tag( ctrl_ber, &len ) == LDAP_SYNC_TAG_COOKIE ) {
811                         ber_scanf( ctrl_ber, "o}", syncCookie );
812                 }
813                 ber_free( ctrl_ber, 1 );
814                 ldap_controls_free( rctrls );
815         } else {
816 #ifdef NEW_LOGGING
817                 LDAP_LOG( OPERATION, ERR,"syncrepl_message_to_entry : "
818                         " rctrls absent\n", 0, 0, 0 );
819 #else
820                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry :"
821                         " rctrls absent\n", 0, 0, 0 );
822 #endif
823         }
824
825         if ( *syncstate == LDAP_SYNC_PRESENT || *syncstate == LDAP_SYNC_DELETE ) {
826                 goto done;
827         }
828
829         if ( *modlist == NULL ) {
830 #ifdef NEW_LOGGING
831                 LDAP_LOG( OPERATION, ERR,
832                                 "syncrepl_message_to_entry: no attributes\n", 0, 0, 0 );
833 #else
834                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
835                                 0, 0, 0 );
836 #endif
837         }
838
839         ml = *modlist;
840         while ( ml != NULL ) {
841                 AttributeDescription *ad = NULL;
842         rc = slap_bv2ad( &ml->sml_type, &ml->sml_desc, &text );
843
844                 if( rc != LDAP_SUCCESS ) {
845                         e = NULL;
846                         goto done;
847                 }
848
849                 ad = ml->sml_desc;
850                 ml->sml_desc = NULL;
851                 ml = ml->sml_next;
852         }
853
854         rc = slap_mods_check( *modlist, 1, &text, txtbuf, textlen, NULL );
855
856         if ( rc != LDAP_SUCCESS ) {
857 #ifdef NEW_LOGGING
858                 LDAP_LOG( OPERATION, ERR,
859                                 "syncrepl_message_to_entry: mods check (%s)\n", text, 0, 0 );
860 #else
861                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
862                                 text, 0, 0 );
863 #endif
864                 return NULL;
865         }
866         
867         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
868         if( rc != LDAP_SUCCESS ) {
869 #ifdef NEW_LOGGING
870                 LDAP_LOG( OPERATION, ERR,
871                                 "syncrepl_message_to_entry: mods2entry (%s)\n", text, 0, 0 );
872 #else
873                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
874                                 text, 0, 0 );
875 #endif
876         }
877
878 done:
879
880         ber_free ( ber, 0 );
881
882         return e;
883 }
884
885 int
886 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
887 {
888         const struct berval *uuid1 = v_uuid1;
889         const struct berval *uuid2 = v_uuid2;
890         int rc = uuid1->bv_len - uuid2->bv_len;
891         if ( rc ) return rc;
892         return ( strcmp( uuid1->bv_val, uuid2->bv_val ) );
893 }
894
895 int
896 syncrepl_entry(
897         syncinfo_t* si,
898         LDAP *ld,
899         Operation *op,
900         Entry* e,
901         Modifications* modlist,
902         int syncstate,
903         struct berval* syncUUID,
904         struct berval* syncCookie,
905         int refresh
906 )
907 {
908         Backend *be = op->o_bd;
909         slap_callback   cb;
910         struct berval   csn_bv = {0, NULL};
911         struct berval   *syncuuid_bv = NULL;
912         char csnbuf[ LDAP_LUTIL_CSNSTR_BUFSIZE ];
913
914         SlapReply       rs = {REP_RESULT};
915         int rc = LDAP_SUCCESS;
916
917         struct berval base_bv = {0, NULL};
918
919         char *filterstr;
920         Filter *filter;
921
922         Attribute *a;
923
924         if ( refresh &&
925                         ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
926                 syncuuid_bv = ber_dupbv( NULL, syncUUID );
927                 avl_insert( &si->presentlist, (caddr_t) syncuuid_bv,
928                                                 syncuuid_cmp, avl_dup_error );
929         }
930
931         if ( syncstate == LDAP_SYNC_PRESENT ) {
932                 if ( e ) {
933                         return 1;
934                 } else {
935                         return 0;
936                 }
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_ndn = NULL;
946
947         filter = str2filter( filterstr );
948         ber_str2bv( filterstr, strlen(filterstr), 1, &op->ors_filterstr );
949         ch_free( filterstr );
950         op->ors_filter = filter;
951         op->ors_scope = LDAP_SCOPE_SUBTREE;
952
953         /* get syncrepl cookie of shadow replica from subentry */
954         ber_str2bv( si->base, strlen(si->base), 1, &base_bv ); 
955         dnPrettyNormal( 0, &base_bv, &op->o_req_dn, &op->o_req_ndn, op->o_tmpmemctx );
956         ch_free( base_bv.bv_val );
957
958         /* set callback function */
959         op->o_callback = &cb;
960         cb.sc_response = dn_callback;
961         cb.sc_private = si;
962
963         si->syncUUID_ndn = NULL;
964
965         rc = be->be_search( op, &rs );
966
967         ch_free( op->o_req_dn.bv_val );
968         ch_free( op->o_req_ndn.bv_val );
969         filter_free( op->ors_filter );
970         ch_free( op->ors_filterstr.bv_val );
971
972         cb.sc_response = null_callback;
973         cb.sc_private = si;
974
975         if ( rc == LDAP_SUCCESS && si->syncUUID_ndn && si->sync_mode != LDAP_SYNC_LOG_MODE ) {
976                 op->o_req_dn = *si->syncUUID_ndn;
977                 op->o_req_ndn = *si->syncUUID_ndn;
978                 op->o_tag = LDAP_REQ_DELETE;
979                 rc = be->be_delete( op, &rs );
980         }
981
982         if ( si->syncUUID_ndn ) {
983                 ber_bvfree( si->syncUUID_ndn );
984         }
985
986         switch ( syncstate ) {
987         case LDAP_SYNC_ADD :
988         case LDAP_SYNC_MODIFY :
989
990                 if ( rc == LDAP_SUCCESS ||
991                          rc == LDAP_REFERRAL ||
992                          rc == LDAP_NO_SUCH_OBJECT ) {
993
994                         attr_delete( &e->e_attrs, slap_schema.si_ad_entryUUID );
995                         attr_merge_normalize_one( e, slap_schema.si_ad_entryUUID, syncUUID, op->o_tmpmemctx );
996
997                         op->o_tag = LDAP_REQ_ADD;
998                         op->ora_e = e;
999                         op->o_req_dn = e->e_name;
1000                         op->o_req_ndn = e->e_nname;
1001                         rc = be->be_add( op, &rs );
1002
1003                         if ( rc != LDAP_SUCCESS ) {
1004                                 if ( rc == LDAP_ALREADY_EXISTS ) {      
1005                                         op->o_tag = LDAP_REQ_MODIFY;
1006                                         op->orm_modlist = modlist;
1007                                         op->o_req_dn = e->e_name;
1008                                         op->o_req_ndn = e->e_nname;
1009                                         rc = be->be_modify( op, &rs );
1010                                         si->e = NULL;
1011                                         if ( rc != LDAP_SUCCESS ) {
1012 #ifdef NEW_LOGGING
1013                                                 LDAP_LOG( OPERATION, ERR,
1014                                                         "syncrepl_entry : be_modify failed (%d)\n",
1015                                                         rc, 0, 0 );
1016 #else
1017                                                 Debug( LDAP_DEBUG_ANY,
1018                                                         "syncrepl_entry : be_modify failed (%d)\n",
1019                                                         rc, 0, 0 );
1020 #endif
1021                                         }
1022                                         return 1;
1023                                 } else if ( rc == LDAP_REFERRAL ||
1024                                                         rc == LDAP_NO_SUCH_OBJECT ) {
1025                                         syncrepl_add_glue( si, ld, op, e,
1026                                                 modlist, syncstate,
1027                                                 syncUUID, syncCookie);
1028                                         si->e = NULL;
1029                                         return 0;
1030                                 } else {
1031 #ifdef NEW_LOGGING
1032                                         LDAP_LOG( OPERATION, ERR,
1033                                                 "syncrepl_entry : be_add failed (%d)\n",
1034                                                 rc, 0, 0 );
1035 #else
1036                                         Debug( LDAP_DEBUG_ANY,
1037                                                 "syncrepl_entry : be_add failed (%d)\n",
1038                                                 rc, 0, 0 );
1039 #endif
1040                                         si->e = NULL;
1041                                         return 1;
1042                                 }
1043                         } else {
1044                                 si->e = NULL;
1045                                 be_entry_release_w( op, e );
1046                                 return 0;
1047                         }
1048                 } else {
1049 #ifdef NEW_LOGGING
1050                         LDAP_LOG( OPERATION, ERR,
1051                                 "syncrepl_entry : be_search failed (%d)\n", rc, 0, 0 );
1052 #else
1053                         Debug( LDAP_DEBUG_ANY,
1054                                 "syncrepl_entry : be_search failed (%d)\n", rc, 0, 0 );
1055 #endif
1056                         si->e = NULL;
1057                         return 1;
1058                 }
1059
1060         case LDAP_SYNC_DELETE :
1061                 if ( si->sync_mode == LDAP_SYNC_LOG_MODE ) {
1062                         op->o_req_dn = *si->syncUUID_ndn;
1063                         op->o_req_ndn = *si->syncUUID_ndn;
1064                         op->o_tag = LDAP_REQ_DELETE;
1065                         rc = be->be_delete( op, &rs );
1066                 }
1067                 /* Already deleted otherwise */
1068                 return 1;
1069
1070         default :
1071 #ifdef NEW_LOGGING
1072                 LDAP_LOG( OPERATION, ERR,
1073                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1074 #else
1075                 Debug( LDAP_DEBUG_ANY,
1076                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1077 #endif
1078                 return 1;
1079         }
1080 }
1081
1082 static void
1083 syncrepl_del_nonpresent(
1084         LDAP *ld,
1085         Operation *op
1086 )
1087 {
1088         Backend* be = op->o_bd;
1089         syncinfo_t *si = op->o_si;
1090         slap_callback   cb;
1091         struct berval   base_bv = {0, NULL};
1092         Filter *filter;
1093         SlapReply       rs = {REP_RESULT};
1094         struct berval   filterstr_bv = {0, NULL};
1095         struct nonpresent_entry *np_list, *np_prev;
1096
1097         ber_str2bv( si->base, strlen(si->base), 1, &base_bv ); 
1098         dnPrettyNormal(0, &base_bv, &op->o_req_dn, &op->o_req_ndn, op->o_tmpmemctx );
1099         ch_free( base_bv.bv_val );
1100
1101         filter = str2filter( si->filterstr );
1102
1103         cb.sc_response = nonpresent_callback;
1104         cb.sc_private = si;
1105
1106         op->o_callback = &cb;
1107         op->o_tag = LDAP_REQ_SEARCH;
1108         op->ors_scope = si->scope;
1109         op->ors_deref = LDAP_DEREF_NEVER;
1110         op->ors_slimit = 0;
1111         op->ors_tlimit = 0;
1112         op->ors_attrsonly = 0;
1113         op->ors_attrs = NULL;
1114         op->ors_filter = filter;
1115         ber_str2bv( si->filterstr, strlen( si->filterstr ), 1, &op->ors_filterstr );
1116
1117         be->be_search( op, &rs );
1118
1119         if ( !LDAP_LIST_EMPTY( &si->nonpresentlist ) ) {
1120                 np_list = LDAP_LIST_FIRST( &si->nonpresentlist );
1121                 while ( np_list != NULL ) {
1122                         LDAP_LIST_REMOVE( np_list, np_link );
1123                         np_prev = np_list;
1124                         np_list = LDAP_LIST_NEXT( np_list, np_link );
1125                         op->o_tag = LDAP_REQ_DELETE;
1126                         op->o_callback = &cb;
1127                         cb.sc_response = null_callback;
1128                         cb.sc_private = si;
1129                         op->o_req_dn = *np_prev->dn;
1130                         op->o_req_ndn = *np_prev->ndn;
1131                         op->o_bd->be_delete( op, &rs );
1132                         ber_bvfree( np_prev->dn );
1133                         ber_bvfree( np_prev->ndn );
1134                         op->o_req_dn.bv_val = NULL;
1135                         op->o_req_ndn.bv_val = NULL;
1136                         ch_free( np_prev );
1137                 }
1138         }
1139
1140         if ( op->o_req_dn.bv_val )
1141                 ch_free( op->o_req_dn.bv_val );
1142         if ( op->o_req_ndn.bv_val )
1143                 ch_free( op->o_req_ndn.bv_val );
1144         filter_free( op->ors_filter );
1145         ch_free( op->ors_filterstr.bv_val );
1146
1147         return;
1148 }
1149
1150
1151 void
1152 syncrepl_add_glue(
1153         syncinfo_t *si,
1154         LDAP *ld,
1155         Operation* op,
1156         Entry *e,
1157         Modifications* modlist,
1158         int syncstate,
1159         struct berval* syncUUID,
1160         struct berval* syncCookie
1161 )
1162 {
1163         Backend *be = op->o_bd;
1164         struct berval   uuid_bv = {0, NULL};
1165         slap_callback cb;
1166         Attribute       *a;
1167         int     rc;
1168         char    uuidbuf[ LDAP_LUTIL_UUIDSTR_BUFSIZE ];
1169         int levels = 0;
1170         int i, j, k;
1171         struct berval dn = {0, NULL};
1172         struct berval pdn = {0, NULL};
1173         struct berval ndn = {0, NULL};
1174         struct berval rdn = {0, NULL};
1175         Entry   *glue;
1176         SlapReply       rs = {REP_RESULT};
1177         Connection *conn = op->o_conn;
1178         char* ptr;
1179
1180         op->o_tag = LDAP_REQ_ADD;
1181         op->o_callback = &cb;
1182         cb.sc_response = null_callback;
1183         cb.sc_private = si;
1184
1185         ber_dupbv( &dn, &e->e_nname );
1186         ber_dupbv( &pdn, &e->e_nname );
1187
1188         ptr = dn.bv_val;
1189         while ( !be_issuffix ( be, &pdn )) {
1190                 dnParent( &dn, &pdn );
1191                 dn.bv_val = pdn.bv_val;
1192                 dn.bv_len = pdn.bv_len;
1193                 levels++;
1194         }
1195         ch_free( ptr );
1196
1197         for ( i = 0; i <= levels; i++ ) {
1198                 glue = (Entry*) ch_calloc( 1, sizeof(Entry) );
1199                 ber_dupbv( &dn, &e->e_nname );
1200                 j = levels - i;
1201
1202                 ptr = dn.bv_val;
1203                 for ( k = 0; k < j; k++ ) {
1204                         dnParent( &dn, &pdn );
1205                         dn.bv_val = pdn.bv_val;
1206                         dn.bv_len = pdn.bv_len;
1207                 }
1208
1209                 dnPrettyNormal( 0, &dn, &pdn, &ndn, op->o_tmpmemctx );
1210                 ber_dupbv( &glue->e_name, &pdn );
1211                 ber_dupbv( &glue->e_nname, &ndn );
1212                 ch_free( ptr );
1213                 ch_free( pdn.bv_val );
1214                 ch_free( ndn.bv_val );
1215
1216                 a = ch_calloc( 1, sizeof( Attribute ));
1217                 a->a_desc = slap_schema.si_ad_objectClass;
1218
1219                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1220                 ber_str2bv( "top", strlen("top"), 1, &a->a_vals[0] );
1221                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_vals[1] );
1222                 a->a_vals[2].bv_len = 0;
1223                 a->a_vals[2].bv_val = NULL;
1224
1225                 a->a_nvals = ch_calloc( 3, sizeof( struct berval ));
1226                 ber_str2bv( "top", strlen("top"), 1, &a->a_nvals[0] );
1227                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_nvals[1] );
1228                 a->a_nvals[2].bv_len = 0;
1229                 a->a_nvals[2].bv_val = NULL;
1230
1231                 a->a_next = glue->e_attrs;
1232                 glue->e_attrs = a;
1233
1234                 a = ch_calloc( 1, sizeof( Attribute ));
1235                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1236
1237                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1238                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_vals[0] );
1239                 a->a_vals[1].bv_len = 0;
1240                 a->a_vals[1].bv_val = NULL;
1241
1242                 a->a_nvals = ch_calloc( 2, sizeof( struct berval ));
1243                 ber_str2bv( "glue", strlen("glue"), 1, &a->a_nvals[0] );
1244                 a->a_nvals[1].bv_len = 0;
1245                 a->a_nvals[1].bv_val = NULL;
1246
1247                 a->a_next = glue->e_attrs;
1248                 glue->e_attrs = a;
1249
1250                 if ( !strcmp( e->e_nname.bv_val, glue->e_nname.bv_val )) {
1251                         op->o_req_dn = e->e_name;
1252                         op->o_req_ndn = e->e_nname;
1253                         op->ora_e = e;
1254                         rc = be->be_add ( op, &rs );
1255                         if ( rc == LDAP_SUCCESS )
1256                                 be_entry_release_w( op, e );
1257                         else 
1258                                 entry_free( e );
1259                         entry_free( glue );
1260                 } else {
1261                         op->o_req_dn = glue->e_name;
1262                         op->o_req_ndn = glue->e_nname;
1263                         op->ora_e = glue;
1264                         rc = be->be_add ( op, &rs );
1265                         if ( rc == LDAP_SUCCESS ) {
1266                                 be_entry_release_w( op, glue );
1267                         } else {
1268                         /* incl. ALREADY EXIST */
1269                                 entry_free( glue );
1270                         }
1271                 }
1272         }
1273
1274         return;
1275 }
1276
1277 void
1278 syncrepl_updateCookie(
1279         syncinfo_t *si,
1280         LDAP *ld,
1281         Operation *op,
1282         struct berval *pdn,
1283         struct berval *syncCookie
1284 )
1285 {
1286         Backend *be = op->o_bd;
1287         Modifications *ml;
1288         Modifications *mlnext;
1289         Modifications *mod;
1290         Modifications *modlist = NULL;
1291         Modifications **modtail = &modlist;
1292
1293         struct berval* ocbva = NULL;
1294         struct berval* cnbva = NULL;
1295         struct berval* ssbva = NULL;
1296         struct berval* scbva = NULL;
1297
1298         char substr[64];
1299         char rdnstr[67];
1300         const char      *text;
1301         char txtbuf[SLAP_TEXT_BUFLEN];
1302         size_t textlen = sizeof txtbuf;
1303
1304         Entry* e = NULL;
1305         int rc;
1306
1307         struct berval sub_bv = { 0, NULL };
1308         struct berval psubrdn = { 0, NULL };
1309         
1310         slap_callback cb;
1311         SlapReply       rs = {REP_RESULT};
1312
1313         ocbva = ( struct berval * ) ch_calloc( 4, sizeof( struct berval ));
1314         cnbva = ( struct berval * ) ch_calloc( 2, sizeof( struct berval ));
1315         ssbva = ( struct berval * ) ch_calloc( 2, sizeof( struct berval ));
1316         scbva = ( struct berval * ) ch_calloc( 2, sizeof( struct berval ));
1317
1318         /* update in memory cookie */
1319         if ( si->syncCookie != NULL ) {
1320                 ber_bvfree( si->syncCookie );
1321         }
1322         si->syncCookie = ber_dupbv( NULL, syncCookie );
1323         ber_str2bv( "top", strlen("top"), 1, &ocbva[0] );
1324         ber_str2bv( "subentry", strlen("subentry"), 1, &ocbva[1] );
1325         ber_str2bv( "syncConsumerSubentry",
1326                         strlen("syncConsumerSubentry"), 1, &ocbva[2] );
1327         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1328         mod->sml_op = LDAP_MOD_REPLACE;
1329         ber_str2bv( "objectClass", strlen("objectClass"), 1, &mod->sml_type );
1330         mod->sml_bvalues = ocbva;
1331         *modtail = mod;
1332         modtail = &mod->sml_next;
1333
1334         sprintf( substr, "syncrepl%d", si->id );
1335         sprintf( rdnstr, "cn=%s", substr );
1336         ber_str2bv( substr, strlen( substr ), 1, &cnbva[0] );
1337         ber_str2bv( rdnstr, strlen( rdnstr ), 1, &psubrdn );
1338         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1339         mod->sml_op = LDAP_MOD_REPLACE;
1340         ber_str2bv( "cn", strlen("cn"), 1, &mod->sml_type );
1341         mod->sml_bvalues = cnbva;
1342         *modtail = mod;
1343         modtail = &mod->sml_next;
1344
1345         ber_dupbv( &scbva[0], si->syncCookie );
1346         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1347         mod->sml_op = LDAP_MOD_REPLACE;
1348         ber_str2bv( "syncreplCookie", strlen("syncreplCookie"),
1349                                                 1, &mod->sml_type );
1350         mod->sml_bvalues = scbva;
1351         *modtail = mod;
1352         modtail = &mod->sml_next;
1353
1354         ber_str2bv( "{}", strlen("{}"), 1, &ssbva[0] );
1355         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1356         mod->sml_op = LDAP_MOD_REPLACE;
1357         ber_str2bv( "subtreeSpecification",
1358                         strlen("subtreeSpecification"), 1, &mod->sml_type );
1359         mod->sml_bvalues = ssbva;
1360         *modtail = mod;
1361         modtail = &mod->sml_next;
1362
1363         rc = slap_mods_check( modlist, 1, &text, txtbuf, textlen, NULL );
1364
1365         if ( rc != LDAP_SUCCESS ) {
1366 #ifdef NEW_LOGGING
1367                 LDAP_LOG( OPERATION, ERR,
1368                                 "syncrepl_updateCookie: mods check (%s)\n", text, 0, 0 );
1369 #else
1370                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods check (%s)\n",
1371                          text, 0, 0 );
1372 #endif
1373         }
1374
1375         op->o_tag = LDAP_REQ_ADD;
1376         rc = slap_mods_opattrs( op, modlist, modtail,
1377                                                          &text,txtbuf, textlen );
1378
1379         for ( ml = modlist; ml != NULL; ml = mlnext ) {
1380                 mlnext = ml->sml_next;
1381                 ml->sml_op = LDAP_MOD_REPLACE;
1382         }
1383
1384         if( rc != LDAP_SUCCESS ) {
1385 #ifdef NEW_LOGGING
1386                 LDAP_LOG( OPERATION, ERR,
1387                                 "syncrepl_updateCookie: mods opattrs (%s)\n", text, 0, 0 );
1388 #else
1389                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods opattrs (%s)\n",
1390                          text, 0, 0 );
1391 #endif
1392         }
1393
1394         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1395
1396         build_new_dn( &sub_bv, pdn, &psubrdn, NULL );
1397         dnPrettyNormal( NULL, &sub_bv, &e->e_name, &e->e_nname, NULL );
1398         ch_free( sub_bv.bv_val );
1399         ch_free( psubrdn.bv_val );
1400
1401         e->e_attrs = NULL;
1402
1403         rc = slap_mods2entry( modlist, &e, 1, 1, &text, txtbuf, textlen );
1404
1405         if( rc != LDAP_SUCCESS ) {
1406 #ifdef NEW_LOGGING
1407                 LDAP_LOG( OPERATION, ERR,
1408                                 "syncrepl_updateCookie: mods2entry (%s)\n", text, 0, 0 );
1409 #else
1410                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods2entry (%s)\n",
1411                          text, 0, 0 );
1412 #endif
1413         }
1414
1415         cb.sc_response = null_callback;
1416         cb.sc_private = si;
1417
1418         op->o_callback = &cb;
1419         op->o_req_dn = e->e_name;
1420         op->o_req_ndn = e->e_nname;
1421
1422         /* update persistent cookie */
1423 update_cookie_retry:
1424         op->o_tag = LDAP_REQ_MODIFY;
1425         op->orm_modlist = modlist;
1426         rc = be->be_modify( op, &rs );
1427
1428         if ( rc != LDAP_SUCCESS ) {
1429                 if ( rc == LDAP_REFERRAL ||
1430                          rc == LDAP_NO_SUCH_OBJECT ) {
1431                         op->o_tag = LDAP_REQ_ADD;
1432                         op->ora_e = e;
1433                         rc = be->be_add( op, &rs );
1434                         if ( rc != LDAP_SUCCESS ) {
1435                                 if ( rc == LDAP_ALREADY_EXISTS ) {
1436                                         goto update_cookie_retry;
1437                                 } else if ( rc == LDAP_REFERRAL ||
1438                                                         rc == LDAP_NO_SUCH_OBJECT ) {
1439 #ifdef NEW_LOGGING
1440                                         LDAP_LOG( OPERATION, ERR,
1441                                                 "cookie will be non-persistent\n",
1442                                                 0, 0, 0 );
1443 #else
1444                                         Debug( LDAP_DEBUG_ANY,
1445                                                 "cookie will be non-persistent\n",
1446                                                 0, 0, 0 );
1447 #endif
1448                                 } else {
1449 #ifdef NEW_LOGGING
1450                                         LDAP_LOG( OPERATION, ERR,
1451                                                 "be_add failed (%d)\n",
1452                                                 rc, 0, 0 );
1453 #else
1454                                         Debug( LDAP_DEBUG_ANY,
1455                                                 "be_add failed (%d)\n",
1456                                                 rc, 0, 0 );
1457 #endif
1458                                 }
1459                         } else {
1460                                 be_entry_release_w( op, e );
1461                                 goto done;
1462                         }
1463                 } else {
1464 #ifdef NEW_LOGGING
1465                         LDAP_LOG( OPERATION, ERR,
1466                                 "be_modify failed (%d)\n", rc, 0, 0 );
1467 #else
1468                         Debug( LDAP_DEBUG_ANY,
1469                                 "be_modify failed (%d)\n", rc, 0, 0 );
1470 #endif
1471                 }
1472         }
1473
1474 done :
1475
1476         if ( e != NULL ) {
1477                 entry_free( e );
1478         }
1479
1480         if ( modlist ) {
1481                 slap_mods_free( modlist );
1482         }
1483
1484         return;
1485 }
1486
1487 void
1488 avl_ber_bvfree( void *bv )
1489 {
1490         if( bv == NULL ) {
1491                 return;
1492         }
1493         if ( ((struct berval *)bv)->bv_val != NULL ) {
1494                 ch_free ( ((struct berval *)bv)->bv_val );
1495         }
1496         ch_free ( (char *) bv );
1497 }
1498
1499 static int
1500 cookie_callback(
1501         Operation* op,
1502         SlapReply* rs
1503 )
1504 {
1505         syncinfo_t *si = op->o_callback->sc_private;
1506         Attribute *a;
1507
1508         if ( rs->sr_type != REP_SEARCH ) return LDAP_SUCCESS;
1509
1510         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_syncreplCookie );
1511
1512         if ( a == NULL ) {
1513                 si->syncCookie = NULL;
1514         } else {
1515                 si->syncCookie = ber_dupbv( NULL, &a->a_vals[0] );
1516         }
1517         return LDAP_SUCCESS;
1518 }
1519
1520 static int
1521 dn_callback(
1522         Operation*      op,
1523         SlapReply*      rs
1524 )
1525 {
1526         syncinfo_t *si = op->o_callback->sc_private;
1527
1528         if ( rs->sr_type == REP_SEARCH ) {
1529                 if ( si->syncUUID_ndn != NULL ) {
1530 #ifdef NEW_LOGGING
1531                         LDAP_LOG( OPERATION, ERR,
1532                                 "dn_callback : multiple entries match dn\n", 0, 0, 0 );
1533 #else
1534                         Debug( LDAP_DEBUG_ANY,
1535                                 "dn_callback : multiple entries match dn\n", 0, 0, 0 );
1536 #endif
1537                 } else {
1538                         if ( rs->sr_entry == NULL ) {
1539                                 si->syncUUID_ndn = NULL;
1540                         } else {
1541                                 si->syncUUID_ndn = ber_dupbv( NULL, &rs->sr_entry->e_nname );
1542                         }
1543                 }
1544         }
1545
1546         return LDAP_SUCCESS;
1547 }
1548
1549 static int
1550 nonpresent_callback(
1551         Operation*      op,
1552         SlapReply*      rs
1553 )
1554 {
1555         syncinfo_t *si = op->o_callback->sc_private;
1556         Attribute *a;
1557         int count = 0;
1558         struct berval* present_uuid = NULL;
1559         slap_callback cb;
1560         SlapReply       rs_cb = {REP_RESULT};
1561         struct nonpresent_entry *np_entry;
1562
1563         if ( rs->sr_type == REP_RESULT ) {
1564                 count = avl_free( si->presentlist, avl_ber_bvfree );
1565                 si->presentlist = NULL;
1566                 return LDAP_SUCCESS;
1567         } else if ( rs->sr_type == REP_SEARCH ) {
1568                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
1569
1570                 if ( a == NULL )
1571                         return 0;
1572
1573                 present_uuid = avl_find( si->presentlist, &a->a_vals[0], syncuuid_cmp );
1574
1575                 if ( present_uuid == NULL ) {
1576                         np_entry = (struct nonpresent_entry *)
1577                                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
1578                         np_entry->dn = ber_dupbv( NULL, &rs->sr_entry->e_name );
1579                         np_entry->ndn = ber_dupbv( NULL, &rs->sr_entry->e_nname );
1580                         LDAP_LIST_INSERT_HEAD( &si->nonpresentlist, np_entry, np_link );
1581                 } else {
1582                         avl_delete( &si->presentlist,
1583                                         &a->a_vals[0], syncuuid_cmp );
1584                         ch_free( present_uuid->bv_val );
1585                         ch_free( present_uuid );
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 }