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