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