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