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