]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
Fix modtail initialization in loop
[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         int rc = LDAP_SUCCESS;
894         int first = 0;
895         int dostop = 0;
896         ber_socket_t s;
897         int i, defer = 1;
898         Backend *be;
899
900         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
901
902         if ( si == NULL )
903                 return NULL;
904
905         switch( abs( si->si_type )) {
906         case LDAP_SYNC_REFRESH_ONLY:
907         case LDAP_SYNC_REFRESH_AND_PERSIST:
908                 break;
909         default:
910                 return NULL;
911         }
912
913         if ( slapd_shutdown && si->si_ld ) {
914                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
915                 connection_client_stop( s );
916                 ldap_unbind( si->si_ld );
917                 si->si_ld = NULL;
918                 return NULL;
919         }
920
921         connection_fake_init( &conn, &op, ctx );
922
923         /* use global malloc for now */
924         op.o_tmpmemctx = NULL;
925         op.o_tmpmfuncs = &ch_mfuncs;
926
927         op.o_dn = si->si_updatedn;
928         op.o_ndn = si->si_updatedn;
929         op.o_managedsait = 1;
930         op.o_bd = be = si->si_be;
931
932         op.o_sync_state.ctxcsn = NULL;
933         op.o_sync_state.sid = -1;
934         op.o_sync_state.octet_str = NULL;
935         op.o_sync_slog_size = -1;
936         LDAP_STAILQ_FIRST( &op.o_sync_slog_list ) = NULL;
937         op.o_sync_slog_list.stqh_last = &LDAP_STAILQ_FIRST(&op.o_sync_slog_list);
938
939         /* Establish session, do search */
940         if ( !si->si_ld ) {
941                 first = 1;
942                 si->si_refreshDelete = 0;
943                 si->si_refreshPresent = 0;
944                 rc = do_syncrep1( &op, si );
945         }
946
947         /* Process results */
948         if ( rc == LDAP_SUCCESS ) {
949                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
950
951                 rc = do_syncrep2( &op, si );
952
953                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
954                         /* If we succeeded, enable the connection for further listening.
955                          * If we failed, tear down the connection and reschedule.
956                          */
957                         if ( rc == LDAP_SUCCESS ) {
958                                 if ( first ) {
959                                         rc = connection_client_setup( s, do_syncrepl, arg );
960                                 } else {
961                                         connection_client_enable( s );
962                                 } 
963                         } else if ( !first ) {
964                                 dostop = 1;
965                         }
966                 } else {
967                         if ( rc == -2 ) rc = 0;
968                 }
969         }
970
971         /* At this point, we have 4 cases:
972          * 1) for any hard failure, give up and remove this task
973          * 2) for ServerDown, reschedule this task to run
974          * 3) for Refresh and Success, reschedule to run
975          * 4) for Persist and Success, reschedule to defer
976          */
977         ldap_pvt_thread_mutex_lock( &syncrepl_rq.rq_mutex );
978
979         if ( ldap_pvt_runqueue_isrunning( &syncrepl_rq, rtask )) {
980                 ldap_pvt_runqueue_stoptask( &syncrepl_rq, rtask );
981         }
982
983         if ( dostop ) {
984                 connection_client_stop( s );
985         }
986
987         if ( rc == LDAP_SUCCESS ) {
988                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
989                         defer = 0;
990                 }
991                 rtask->interval.tv_sec = si->si_interval;
992                 ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, defer );
993                 if ( si->si_retrynum ) {
994                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
995                                 si->si_retrynum[i] = si->si_retrynum_init[i];
996                         }
997                         si->si_retrynum[i] = -2;
998                 }
999         } else {
1000                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1001                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
1002                                 break;
1003                 }
1004
1005                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
1006                         ldap_pvt_runqueue_remove( &syncrepl_rq, rtask );
1007                         LDAP_STAILQ_REMOVE( &be->be_syncinfo, si, syncinfo_s, si_next );
1008                         syncinfo_free( si );
1009                 } else if ( si->si_retrynum[i] >= -1 ) {
1010                         if ( si->si_retrynum[i] > 0 )
1011                                 si->si_retrynum[i]--;
1012                         rtask->interval.tv_sec = si->si_retryinterval[i];
1013                         ldap_pvt_runqueue_resched( &syncrepl_rq, rtask, 0 );
1014                         slap_wake_listener();
1015                 }
1016         }
1017         
1018         ldap_pvt_thread_mutex_unlock( &syncrepl_rq.rq_mutex );
1019
1020         return NULL;
1021 }
1022
1023 int
1024 syncrepl_message_to_entry(
1025         syncinfo_t      *si,
1026         Operation       *op,
1027         LDAPMessage     *msg,
1028         Modifications   **modlist,
1029         Entry                   **entry,
1030         int             syncstate
1031 )
1032 {
1033         Entry           *e = NULL;
1034         BerElement      *ber = NULL;
1035         Modifications   tmp;
1036         Modifications   *mod;
1037         Modifications   **modtail = modlist;
1038
1039         const char      *text;
1040         char txtbuf[SLAP_TEXT_BUFLEN];
1041         size_t textlen = sizeof txtbuf;
1042
1043         struct berval   bdn = {0, NULL}, dn, ndn;
1044         int             rc;
1045
1046         *modlist = NULL;
1047
1048         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1049                 Debug( LDAP_DEBUG_ANY,
1050                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1051                 return -1;
1052         }
1053
1054         op->o_tag = LDAP_REQ_ADD;
1055
1056         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1057
1058         if ( rc != LDAP_SUCCESS ) {
1059                 Debug( LDAP_DEBUG_ANY,
1060                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1061                 return rc;
1062         }
1063
1064         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1065         ber_dupbv( &op->o_req_dn, &dn );
1066         ber_dupbv( &op->o_req_ndn, &ndn );
1067         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1068         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1069
1070         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1071                 if ( entry )
1072                         *entry = NULL;
1073                 return LDAP_SUCCESS;
1074         }
1075
1076         if ( entry == NULL ) {
1077                 return -1;
1078         }
1079
1080         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1081         *entry = e;
1082         e->e_name = op->o_req_dn;
1083         e->e_nname = op->o_req_ndn;
1084
1085         while ( ber_remaining( ber ) ) {
1086                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1087                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1088                 {
1089                         break;
1090                 }
1091
1092                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1093
1094                 mod->sml_op = LDAP_MOD_REPLACE;
1095                 mod->sml_next = NULL;
1096                 mod->sml_desc = NULL;
1097                 mod->sml_type = tmp.sml_type;
1098                 mod->sml_values = tmp.sml_values;
1099                 mod->sml_nvalues = NULL;
1100
1101                 *modtail = mod;
1102                 modtail = &mod->sml_next;
1103         }
1104
1105         if ( *modlist == NULL ) {
1106                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1107                         0, 0, 0 );
1108                 rc = -1;
1109                 goto done;
1110         }
1111
1112         rc = slap_mods_check( *modlist, 1, &text, txtbuf, textlen, NULL );
1113
1114         if ( rc != LDAP_SUCCESS ) {
1115                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1116                         text, 0, 0 );
1117                 goto done;
1118         }
1119
1120         /* Strip out dynamically generated attrs */
1121         for ( modtail = modlist; *modtail ; ) {
1122                 mod = *modtail;
1123                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1124                         *modtail = mod->sml_next;
1125                         slap_mod_free( &mod->sml_mod, 0 );
1126                         ch_free( mod );
1127                 } else {
1128                         modtail = &mod->sml_next;
1129                 }
1130         }
1131
1132         /* Strip out attrs in exattrs list */
1133         for ( modtail = modlist; *modtail ; ) {
1134                 mod = *modtail;
1135                 if ( ldap_charray_inlist( si->si_exattrs,
1136                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1137                         *modtail = mod->sml_next;
1138                         slap_mod_free( &mod->sml_mod, 0 );
1139                         ch_free( mod );
1140                 } else {
1141                         modtail = &mod->sml_next;
1142                 }
1143         }
1144         
1145         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1146         if( rc != LDAP_SUCCESS ) {
1147                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1148                         text, 0, 0 );
1149         }
1150
1151 done:
1152         ber_free ( ber, 0 );
1153         if ( rc != LDAP_SUCCESS ) {
1154                 if ( e ) {
1155                         entry_free( e );
1156                         *entry = e = NULL;
1157                 }
1158         }
1159
1160         return rc;
1161 }
1162
1163 int
1164 syncrepl_entry(
1165         syncinfo_t* si,
1166         Operation *op,
1167         Entry* entry,
1168         Modifications* modlist,
1169         int syncstate,
1170         struct berval* syncUUID,
1171         struct sync_cookie* syncCookie_req )
1172 {
1173         Backend *be = op->o_bd;
1174         slap_callback   cb = { NULL };
1175         struct berval   *syncuuid_bv = NULL;
1176         struct berval   syncUUID_strrep = BER_BVNULL;
1177         struct berval   uuid_bv = BER_BVNULL;
1178
1179         SlapReply       rs_search = {REP_RESULT};
1180         SlapReply       rs_delete = {REP_RESULT};
1181         SlapReply       rs_add = {REP_RESULT};
1182         SlapReply       rs_modify = {REP_RESULT};
1183         Filter f = {0};
1184         AttributeAssertion ava = {0};
1185         int rc = LDAP_SUCCESS;
1186         int ret = LDAP_SUCCESS;
1187
1188         struct berval pdn = BER_BVNULL;
1189         struct berval org_req_dn = BER_BVNULL;
1190         struct berval org_req_ndn = BER_BVNULL;
1191         struct berval org_dn = BER_BVNULL;
1192         struct berval org_ndn = BER_BVNULL;
1193         int     org_managedsait;
1194
1195         switch( syncstate ) {
1196         case LDAP_SYNC_PRESENT:
1197                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1198                                         "syncrepl_entry",
1199                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1200                 break;
1201         case LDAP_SYNC_ADD:
1202                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1203                                         "syncrepl_entry",
1204                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1205                 break;
1206         case LDAP_SYNC_DELETE:
1207                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1208                                         "syncrepl_entry",
1209                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1210                 break;
1211         case LDAP_SYNC_MODIFY:
1212                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1213                                         "syncrepl_entry",
1214                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1215                 break;
1216         default:
1217                 Debug( LDAP_DEBUG_ANY, "%s: %s\n",
1218                                         "syncrepl_entry",
1219                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1220         }
1221
1222         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1223                 if ( !si->si_refreshPresent ) {
1224                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1225                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1226                                 syncuuid_cmp, avl_dup_error );
1227                 }
1228         }
1229
1230         if ( syncstate == LDAP_SYNC_PRESENT ) {
1231                 return 0;
1232         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1233                 if ( entry == NULL ) {
1234                         return 0;
1235                 }
1236         }
1237
1238         f.f_choice = LDAP_FILTER_EQUALITY;
1239         f.f_ava = &ava;
1240         ava.aa_desc = slap_schema.si_ad_entryUUID;
1241         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1242         ava.aa_value = *syncUUID;
1243         op->ors_filter = &f;
1244
1245         op->ors_filterstr.bv_len = STRLENOF( "entryUUID=" ) + syncUUID->bv_len;
1246         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1247                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1248         AC_MEMCPY( op->ors_filterstr.bv_val, "entryUUID=", STRLENOF( "entryUUID=" ) );
1249         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "entryUUID=" )],
1250                 syncUUID->bv_val, syncUUID->bv_len );
1251         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1252
1253         op->o_tag = LDAP_REQ_SEARCH;
1254         op->ors_scope = LDAP_SCOPE_SUBTREE;
1255
1256         /* get syncrepl cookie of shadow replica from subentry */
1257         op->o_req_dn = si->si_base;
1258         op->o_req_ndn = si->si_base;
1259
1260         op->o_time = slap_get_time();
1261         op->ors_tlimit = SLAP_NO_LIMIT;
1262         op->ors_slimit = 1;
1263
1264         op->ors_attrs = slap_anlist_no_attrs;
1265         op->ors_attrsonly = 1;
1266
1267         /* set callback function */
1268         op->o_callback = &cb;
1269         cb.sc_response = dn_callback;
1270         cb.sc_private = si;
1271
1272         BER_BVZERO( &si->si_syncUUID_ndn );
1273
1274         if ( limits_check( op, &rs_search ) == 0 ) {
1275                 rc = be->be_search( op, &rs_search );
1276                 Debug( LDAP_DEBUG_SYNC,
1277                                 "syncrepl_entry: %s (%d)\n", 
1278                                 "be_search", rc, 0 );
1279         }
1280
1281         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1282                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1283         }
1284
1285         cb.sc_response = null_callback;
1286         cb.sc_private = si;
1287
1288         if ( entry && entry->e_name.bv_val ) {
1289                 Debug( LDAP_DEBUG_SYNC,
1290                                 "syncrepl_entry: %s\n",
1291                                 entry->e_name.bv_val, 0, 0 );
1292         } else {
1293                 Debug( LDAP_DEBUG_SYNC,
1294                                 "syncrepl_entry: %s\n",
1295                                 si->si_syncUUID_ndn.bv_val, 0, 0 );
1296         }
1297
1298         if ( rs_search.sr_err == LDAP_SUCCESS &&
1299                  !BER_BVISNULL( &si->si_syncUUID_ndn ))
1300         {
1301                 char *subseq_ptr;
1302
1303                 if ( syncstate != LDAP_SYNC_DELETE ) {
1304                         op->o_no_psearch = 1;
1305                 }
1306
1307                 ber_dupbv( &op->o_sync_csn, syncCookie_req->ctxcsn );
1308                 if ( !BER_BVISNULL( &op->o_sync_csn ) ) {
1309                         subseq_ptr = strstr( op->o_sync_csn.bv_val, "#0000" );
1310                         subseq_ptr += 4;
1311                         *subseq_ptr = '1';
1312                 }
1313                 
1314                 op->o_req_dn = si->si_syncUUID_ndn;
1315                 op->o_req_ndn = si->si_syncUUID_ndn;
1316                 op->o_tag = LDAP_REQ_DELETE;
1317                 rc = be->be_delete( op, &rs_delete );
1318                 Debug( LDAP_DEBUG_SYNC,
1319                                 "syncrepl_entry: %s (%d)\n", 
1320                                 "be_delete", rc, 0 );
1321
1322                 org_req_dn = op->o_req_dn;
1323                 org_req_ndn = op->o_req_ndn;
1324                 org_dn = op->o_dn;
1325                 org_ndn = op->o_ndn;
1326                 org_managedsait = get_manageDSAit( op );
1327                 op->o_dn = op->o_bd->be_rootdn;
1328                 op->o_ndn = op->o_bd->be_rootndn;
1329                 op->o_managedsait = 1;
1330
1331                 while ( rs_delete.sr_err == LDAP_SUCCESS && op->o_delete_glue_parent ) {
1332                         op->o_delete_glue_parent = 0;
1333                         if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1334                                 slap_callback cb = { NULL };
1335                                 cb.sc_response = slap_null_cb;
1336                                 dnParent( &op->o_req_ndn, &pdn );
1337                                 op->o_req_dn = pdn;
1338                                 op->o_req_ndn = pdn;
1339                                 op->o_callback = &cb;
1340                                 op->o_bd->be_delete( op, &rs_delete );
1341                         } else {
1342                                 break;
1343                     }
1344                 }
1345
1346                 op->o_managedsait = org_managedsait;
1347                 op->o_dn = org_dn;
1348                 op->o_ndn = org_ndn;
1349                 op->o_req_dn = org_req_dn;
1350                 op->o_req_ndn = org_req_ndn;
1351                 op->o_delete_glue_parent = 0;
1352
1353                 op->o_no_psearch = 0;
1354         }
1355
1356         switch ( syncstate ) {
1357         case LDAP_SYNC_ADD:
1358         case LDAP_SYNC_MODIFY:
1359                 if ( rs_search.sr_err == LDAP_SUCCESS ||
1360                          rs_search.sr_err == LDAP_REFERRAL ||
1361                          rs_search.sr_err == LDAP_NO_SUCH_OBJECT ||
1362                          rs_search.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF )
1363                 {
1364                         attr_delete( &entry->e_attrs, slap_schema.si_ad_entryUUID );
1365                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1366                                 &syncUUID_strrep, syncUUID );
1367
1368                         op->o_tag = LDAP_REQ_ADD;
1369                         op->ora_e = entry;
1370                         op->o_req_dn = entry->e_name;
1371                         op->o_req_ndn = entry->e_nname;
1372
1373                         rc = be->be_add( op, &rs_add );
1374                         Debug( LDAP_DEBUG_SYNC,
1375                                         "syncrepl_entry: %s (%d)\n", 
1376                                         "be_add", rc, 0 );
1377
1378                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1379                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS &&
1380                                          rs_search.sr_err != LDAP_NO_SUCH_OBJECT ) {
1381                                         Modifications *mod;
1382                                         Modifications *modtail = modlist;
1383
1384                                         assert( modlist );
1385
1386                                         for ( mod = modlist; mod != NULL; mod = mod->sml_next ) {
1387                                                 modtail = mod;
1388                                         }
1389
1390                                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1391                                         ber_dupbv( &uuid_bv, syncUUID );
1392                                         mod->sml_op = LDAP_MOD_REPLACE;
1393                                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1394                                         mod->sml_type = mod->sml_desc->ad_cname;
1395                                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1396                                         modtail->sml_next = mod;
1397                                         
1398                                         op->o_tag = LDAP_REQ_MODIFY;
1399                                         op->orm_modlist = modlist;
1400                                         op->o_req_dn = entry->e_name;
1401                                         op->o_req_ndn = entry->e_nname;
1402
1403                                         rc = be->be_modify( op, &rs_modify );
1404                                         Debug( LDAP_DEBUG_SYNC,
1405                                                         "syncrepl_entry: %s (%d)\n", 
1406                                                         "be_modify", rc, 0 );
1407                                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1408                                                 Debug( LDAP_DEBUG_ANY,
1409                                                         "syncrepl_entry : be_modify failed (%d)\n",
1410                                                         rs_modify.sr_err, 0, 0 );
1411                                         }
1412                                         ret = 1;
1413                                         goto done;
1414                                 } else if ( rs_modify.sr_err == LDAP_REFERRAL ||
1415                                                         rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1416                                         syncrepl_add_glue( op, entry );
1417                                         ret = 0;
1418                                         goto done;
1419                                 } else {
1420                                         Debug( LDAP_DEBUG_ANY,
1421                                                 "syncrepl_entry : be_add failed (%d)\n",
1422                                                 rs_add.sr_err, 0, 0 );
1423                                         ret = 1;
1424                                         goto done;
1425                                 }
1426                         } else {
1427                                 be_entry_release_w( op, entry );
1428                                 ret = 0;
1429                                 goto done;
1430                         }
1431                 } else {
1432                         Debug( LDAP_DEBUG_ANY,
1433                                 "syncrepl_entry : be_search failed (%d)\n",
1434                                 rs_search.sr_err, 0, 0 );
1435                         ret = 1;
1436                         goto done;
1437                 }
1438
1439         case LDAP_SYNC_DELETE :
1440                 /* Already deleted */
1441                 ret = 0;
1442                 goto done;
1443
1444         default :
1445                 Debug( LDAP_DEBUG_ANY,
1446                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1447                 ret = 1;
1448                 goto done;
1449         }
1450
1451 done :
1452
1453         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
1454                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1455                 BER_BVZERO( &syncUUID_strrep );
1456         }
1457         if ( !BER_BVISNULL( &si->si_syncUUID_ndn ) ) {
1458                 ch_free( si->si_syncUUID_ndn.bv_val );
1459                 BER_BVZERO( &si->si_syncUUID_ndn );
1460         }
1461         return ret;
1462 }
1463
1464 static struct berval gcbva[] = {
1465         BER_BVC("top"),
1466         BER_BVC("glue"),
1467         BER_BVNULL
1468 };
1469
1470 static void
1471 syncrepl_del_nonpresent(
1472         Operation *op,
1473         syncinfo_t *si )
1474 {
1475         Backend* be = op->o_bd;
1476         slap_callback   cb = { NULL };
1477         SlapReply       rs_search = {REP_RESULT};
1478         SlapReply       rs_delete = {REP_RESULT};
1479         SlapReply       rs_modify = {REP_RESULT};
1480         struct nonpresent_entry *np_list, *np_prev;
1481         int rc;
1482         Modifications *ml;
1483         Modifications *mlnext;
1484         Modifications *mod;
1485         Modifications *modlist = NULL;
1486         Modifications **modtail;
1487         AttributeName   an[2];
1488
1489         struct berval pdn = BER_BVNULL;
1490         struct berval org_req_dn = BER_BVNULL;
1491         struct berval org_req_ndn = BER_BVNULL;
1492         struct berval org_dn = BER_BVNULL;
1493         struct berval org_ndn = BER_BVNULL;
1494         int     org_managedsait;
1495
1496         op->o_req_dn = si->si_base;
1497         op->o_req_ndn = si->si_base;
1498
1499         cb.sc_response = nonpresent_callback;
1500         cb.sc_private = si;
1501
1502         op->o_callback = &cb;
1503         op->o_tag = LDAP_REQ_SEARCH;
1504         op->ors_scope = si->si_scope;
1505         op->ors_deref = LDAP_DEREF_NEVER;
1506         op->o_time = slap_get_time();
1507         op->ors_tlimit = SLAP_NO_LIMIT;
1508         op->ors_slimit = SLAP_NO_LIMIT;
1509
1510         memset( &an[0], 0, 2 * sizeof( AttributeName ) );
1511         an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1512         an[0].an_desc = slap_schema.si_ad_entryUUID;
1513         op->ors_attrs = an;
1514
1515         op->ors_attrsonly = 0;
1516         op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
1517         op->ors_filterstr = si->si_filterstr;
1518
1519         op->o_nocaching = 1;
1520         op->o_managedsait = 0;
1521
1522         if ( limits_check( op, &rs_search ) == 0 ) {
1523                 rc = be->be_search( op, &rs_search );
1524         }
1525
1526         op->o_managedsait = 1;
1527         op->o_nocaching = 0;
1528
1529         if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
1530
1531         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
1532                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
1533                 while ( np_list != NULL ) {
1534                         LDAP_LIST_REMOVE( np_list, npe_link );
1535                         np_prev = np_list;
1536                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
1537                         op->o_tag = LDAP_REQ_DELETE;
1538                         op->o_callback = &cb;
1539                         cb.sc_response = null_callback;
1540                         cb.sc_private = si;
1541                         op->o_req_dn = *np_prev->npe_name;
1542                         op->o_req_ndn = *np_prev->npe_nname;
1543                         rc = op->o_bd->be_delete( op, &rs_delete );
1544
1545                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
1546                                 modtail = &modlist;
1547                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1548                                 mod->sml_op = LDAP_MOD_REPLACE;
1549                                 mod->sml_desc = slap_schema.si_ad_objectClass;
1550                                 mod->sml_type = mod->sml_desc->ad_cname;
1551                                 mod->sml_values = &gcbva[0];
1552                                 *modtail = mod;
1553                                 modtail = &mod->sml_next;
1554
1555                                 mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1556                                 mod->sml_op = LDAP_MOD_REPLACE;
1557                                 mod->sml_desc = slap_schema.si_ad_structuralObjectClass;
1558                                 mod->sml_type = mod->sml_desc->ad_cname;
1559                                 mod->sml_values = &gcbva[1];
1560                                 *modtail = mod;
1561                                 modtail = &mod->sml_next;
1562
1563                                 op->o_tag = LDAP_REQ_MODIFY;
1564                                 op->orm_modlist = modlist;
1565
1566                                 rc = be->be_modify( op, &rs_modify );
1567
1568                                 for ( ml = modlist; ml != NULL; ml = mlnext ) {
1569                                         mlnext = ml->sml_next;
1570                                         free( ml );
1571                                 }
1572                         }
1573
1574                         org_req_dn = op->o_req_dn;
1575                         org_req_ndn = op->o_req_ndn;
1576                         org_dn = op->o_dn;
1577                         org_ndn = op->o_ndn;
1578                         org_managedsait = get_manageDSAit( op );
1579                         op->o_dn = op->o_bd->be_rootdn;
1580                         op->o_ndn = op->o_bd->be_rootndn;
1581                         op->o_managedsait = 1;
1582
1583                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
1584                                         op->o_delete_glue_parent ) {
1585                                 op->o_delete_glue_parent = 0;
1586                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1587                                         slap_callback cb = { NULL };
1588                                         cb.sc_response = slap_null_cb;
1589                                         dnParent( &op->o_req_ndn, &pdn );
1590                                         op->o_req_dn = pdn;
1591                                         op->o_req_ndn = pdn;
1592                                         op->o_callback = &cb;
1593                                         /* give it a root privil ? */
1594                                         op->o_bd->be_delete( op, &rs_delete );
1595                                 } else {
1596                                         break;
1597                             }
1598                         }
1599
1600                         op->o_managedsait = org_managedsait;
1601                         op->o_dn = org_dn;
1602                         op->o_ndn = org_ndn;
1603                         op->o_req_dn = org_req_dn;
1604                         op->o_req_ndn = org_req_ndn;
1605                         op->o_delete_glue_parent = 0;
1606
1607                         ber_bvfree( np_prev->npe_name );
1608                         ber_bvfree( np_prev->npe_nname );
1609                         BER_BVZERO( &op->o_req_dn );
1610                         BER_BVZERO( &op->o_req_ndn );
1611                         ch_free( np_prev );
1612                 }
1613         }
1614
1615         return;
1616 }
1617
1618 void
1619 syncrepl_add_glue(
1620         Operation* op,
1621         Entry *e )
1622 {
1623         Backend *be = op->o_bd;
1624         slap_callback cb = { NULL };
1625         Attribute       *a;
1626         int     rc;
1627         int suffrdns;
1628         int i;
1629         struct berval dn = {0, NULL};
1630         struct berval ndn = {0, NULL};
1631         Entry   *glue;
1632         SlapReply       rs_add = {REP_RESULT};
1633         char    *ptr, *comma;
1634
1635         op->o_tag = LDAP_REQ_ADD;
1636         op->o_callback = &cb;
1637         cb.sc_response = null_callback;
1638         cb.sc_private = NULL;
1639
1640         dn = e->e_name;
1641         ndn = e->e_nname;
1642
1643         /* count RDNs in suffix */
1644         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
1645                 for ( i = 0, ptr = be->be_nsuffix[0].bv_val; ptr; ptr = strchr( ptr, ',' ) ) {
1646                         ptr++;
1647                         i++;
1648                 }
1649                 suffrdns = i;
1650         } else {
1651                 /* suffix is "" */
1652                 suffrdns = 0;
1653         }
1654
1655         /* Start with BE suffix */
1656         for ( i = 0, ptr = NULL; i < suffrdns; i++ ) {
1657                 comma = strrchr( dn.bv_val, ',' );
1658                 if ( ptr ) *ptr = ',';
1659                 if ( comma ) *comma = '\0';
1660                 ptr = comma;
1661         }
1662         if ( ptr ) {
1663                 *ptr++ = ',';
1664                 dn.bv_len -= ptr - dn.bv_val;
1665                 dn.bv_val = ptr;
1666         }
1667         /* the normalizedDNs are always the same length, no counting
1668          * required.
1669          */
1670         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
1671                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
1672                 ndn.bv_len = be->be_nsuffix[0].bv_len;
1673         }
1674
1675         while ( ndn.bv_val > e->e_nname.bv_val ) {
1676                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
1677                 ber_dupbv( &glue->e_name, &dn );
1678                 ber_dupbv( &glue->e_nname, &ndn );
1679
1680                 a = ch_calloc( 1, sizeof( Attribute ));
1681                 a->a_desc = slap_schema.si_ad_objectClass;
1682
1683                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1684                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
1685                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
1686                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
1687
1688                 a->a_nvals = a->a_vals;
1689
1690                 a->a_next = glue->e_attrs;
1691                 glue->e_attrs = a;
1692
1693                 a = ch_calloc( 1, sizeof( Attribute ));
1694                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1695
1696                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1697                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
1698                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
1699
1700                 a->a_nvals = a->a_vals;
1701
1702                 a->a_next = glue->e_attrs;
1703                 glue->e_attrs = a;
1704
1705                 op->o_req_dn = glue->e_name;
1706                 op->o_req_ndn = glue->e_nname;
1707                 op->ora_e = glue;
1708                 rc = be->be_add ( op, &rs_add );
1709                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
1710                         be_entry_release_w( op, glue );
1711                 } else {
1712                 /* incl. ALREADY EXIST */
1713                         entry_free( glue );
1714                 }
1715
1716                 /* Move to next child */
1717                 for (ptr = dn.bv_val-2; ptr > e->e_name.bv_val && *ptr != ','; ptr--) {
1718                         /* empty */
1719                 }
1720                 if ( ptr == e->e_name.bv_val ) break;
1721                 dn.bv_val = ++ptr;
1722                 dn.bv_len = e->e_name.bv_len - (ptr-e->e_name.bv_val);
1723                 for( ptr = ndn.bv_val-2;
1724                         ptr > e->e_nname.bv_val && *ptr != ',';
1725                         ptr--)
1726                 {
1727                         /* empty */
1728                 }
1729                 ndn.bv_val = ++ptr;
1730                 ndn.bv_len = e->e_nname.bv_len - (ptr-e->e_nname.bv_val);
1731         }
1732
1733         op->o_req_dn = e->e_name;
1734         op->o_req_ndn = e->e_nname;
1735         op->ora_e = e;
1736         rc = be->be_add ( op, &rs_add );
1737         if ( rs_add.sr_err == LDAP_SUCCESS ) {
1738                 be_entry_release_w( op, e );
1739         } else {
1740                 entry_free( e );
1741         }
1742
1743         return;
1744 }
1745
1746 static struct berval ocbva[] = {
1747         BER_BVC("top"),
1748         BER_BVC("subentry"),
1749         BER_BVC("syncConsumerSubentry"),
1750         BER_BVNULL
1751 };
1752
1753 static struct berval cnbva[] = {
1754         BER_BVNULL,
1755         BER_BVNULL
1756 };
1757
1758 static struct berval ssbva[] = {
1759         BER_BVC("{}"),
1760         BER_BVNULL
1761 };
1762
1763 static struct berval scbva[] = {
1764         BER_BVNULL,
1765         BER_BVNULL
1766 };
1767
1768 void
1769 syncrepl_updateCookie(
1770         syncinfo_t *si,
1771         Operation *op,
1772         struct berval *pdn,
1773         struct sync_cookie *syncCookie )
1774 {
1775         Backend *be = op->o_bd;
1776         Modifications *ml;
1777         Modifications *mlnext;
1778         Modifications *mod;
1779         Modifications *modlist = NULL;
1780         Modifications **modtail = &modlist;
1781
1782         const char      *text;
1783         char txtbuf[SLAP_TEXT_BUFLEN];
1784         size_t textlen = sizeof txtbuf;
1785
1786         Entry* e = NULL;
1787         int rc;
1788
1789         char syncrepl_cbuf[sizeof(CN_STR SYNCREPL_STR)];
1790         struct berval slap_syncrepl_dn_bv = BER_BVNULL;
1791         struct berval slap_syncrepl_cn_bv = BER_BVNULL;
1792         
1793         slap_callback cb = { NULL };
1794         SlapReply       rs_add = {REP_RESULT};
1795         SlapReply       rs_modify = {REP_RESULT};
1796
1797         slap_sync_cookie_free( &si->si_syncCookie, 0 );
1798         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
1799
1800         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1801         mod->sml_op = LDAP_MOD_REPLACE;
1802         mod->sml_desc = slap_schema.si_ad_objectClass;
1803         mod->sml_type = mod->sml_desc->ad_cname;
1804         mod->sml_values = ocbva;
1805         *modtail = mod;
1806         modtail = &mod->sml_next;
1807
1808         ber_dupbv( &cnbva[0], (struct berval *) &slap_syncrepl_bvc );
1809         assert( si->si_rid < 1000 );
1810         cnbva[0].bv_len = snprintf( cnbva[0].bv_val,
1811                 slap_syncrepl_bvc.bv_len + 1,
1812                 "syncrepl%ld", si->si_rid );
1813         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1814         mod->sml_op = LDAP_MOD_REPLACE;
1815         mod->sml_desc = slap_schema.si_ad_cn;
1816         mod->sml_type = mod->sml_desc->ad_cname;
1817         mod->sml_values = cnbva;
1818         *modtail = mod;
1819         modtail = &mod->sml_next;
1820
1821         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1822         mod->sml_op = LDAP_MOD_REPLACE;
1823         mod->sml_desc = slap_schema.si_ad_subtreeSpecification;
1824         mod->sml_type = mod->sml_desc->ad_cname;
1825         mod->sml_values = ssbva;
1826         *modtail = mod;
1827         modtail = &mod->sml_next;
1828
1829         /* Keep this last, so we can avoid touching the previous
1830          * attributes unnecessarily.
1831          */
1832         if ( scbva[0].bv_val ) ch_free( scbva[0].bv_val );
1833         ber_dupbv( &scbva[0], &si->si_syncCookie.octet_str[0] );
1834         mod = (Modifications *) ch_calloc( 1, sizeof( Modifications ));
1835         mod->sml_op = LDAP_MOD_REPLACE;
1836         mod->sml_desc = slap_schema.si_ad_syncreplCookie;
1837         mod->sml_type = mod->sml_desc->ad_cname;
1838         mod->sml_values = scbva;
1839         *modtail = mod;
1840         modtail = &mod->sml_next;
1841
1842         mlnext = mod;
1843
1844         op->o_tag = LDAP_REQ_ADD;
1845         rc = slap_mods_opattrs( op, modlist, modtail,
1846                  &text, txtbuf, textlen, 0 );
1847
1848         for ( ml = modlist; ml != NULL; ml = ml->sml_next ) {
1849                 ml->sml_op = LDAP_MOD_REPLACE;
1850         }
1851
1852         if( rc != LDAP_SUCCESS ) {
1853                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods opattrs (%s)\n",
1854                          text, 0, 0 );
1855         }
1856
1857         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
1858
1859         slap_syncrepl_cn_bv.bv_val = syncrepl_cbuf;
1860         assert( si->si_rid < 1000 );
1861         slap_syncrepl_cn_bv.bv_len = snprintf( slap_syncrepl_cn_bv.bv_val,
1862                 slap_syncrepl_cn_bvc.bv_len + 1,
1863                 "cn=syncrepl%ld", si->si_rid );
1864
1865         build_new_dn( &slap_syncrepl_dn_bv, pdn, &slap_syncrepl_cn_bv,
1866                 op->o_tmpmemctx );
1867         ber_dupbv( &e->e_name, &slap_syncrepl_dn_bv );
1868         ber_dupbv( &e->e_nname, &slap_syncrepl_dn_bv );
1869
1870         if ( !BER_BVISNULL( &slap_syncrepl_dn_bv ) ) {
1871                 slap_sl_free( slap_syncrepl_dn_bv.bv_val, op->o_tmpmemctx );
1872         }
1873
1874         e->e_attrs = NULL;
1875
1876         rc = slap_mods2entry( modlist, &e, 1, 1, &text, txtbuf, textlen );
1877
1878         if( rc != LDAP_SUCCESS ) {
1879                 Debug( LDAP_DEBUG_ANY, "syncrepl_updateCookie: mods2entry (%s)\n",
1880                          text, 0, 0 );
1881         }
1882
1883         cb.sc_response = null_callback;
1884         cb.sc_private = si;
1885
1886         op->o_callback = &cb;
1887         op->o_req_dn = e->e_name;
1888         op->o_req_ndn = e->e_nname;
1889
1890         /* update persistent cookie */
1891 update_cookie_retry:
1892         op->o_tag = LDAP_REQ_MODIFY;
1893         /* Just modify the cookie value, not the entire entry */
1894         op->orm_modlist = mod;
1895         rc = be->be_modify( op, &rs_modify );
1896
1897         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1898                 if ( rs_modify.sr_err == LDAP_REFERRAL ||
1899                          rs_modify.sr_err == LDAP_NO_SUCH_OBJECT ) {
1900                         op->o_tag = LDAP_REQ_ADD;
1901                         op->ora_e = e;
1902                         rc = be->be_add( op, &rs_add );
1903                         if ( rs_add.sr_err != LDAP_SUCCESS ) {
1904                                 if ( rs_add.sr_err == LDAP_ALREADY_EXISTS ) {
1905                                         goto update_cookie_retry;
1906                                 } else if ( rs_add.sr_err == LDAP_REFERRAL ||
1907                                                         rs_add.sr_err == LDAP_NO_SUCH_OBJECT ) {
1908                                         Debug( LDAP_DEBUG_ANY,
1909                                                 "cookie will be non-persistent\n",
1910                                                 0, 0, 0 );
1911                                 } else {
1912                                         Debug( LDAP_DEBUG_ANY,
1913                                                 "be_add failed (%d)\n", rs_add.sr_err, 0, 0 );
1914                                 }
1915                         } else {
1916                                 be_entry_release_w( op, e );
1917                                 goto done;
1918                         }
1919                 } else {
1920                         Debug( LDAP_DEBUG_ANY,
1921                                 "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
1922                 }
1923         }
1924
1925         if ( e != NULL ) {
1926                 entry_free( e );
1927         }
1928
1929 done :
1930
1931         if ( !BER_BVISNULL( &cnbva[0] ) ) {
1932                 ch_free( cnbva[0].bv_val );
1933                 BER_BVZERO( &cnbva[0] );
1934         }
1935         if ( !BER_BVISNULL( &scbva[0] ) ) {
1936                 ch_free( scbva[0].bv_val );
1937                 BER_BVZERO( &scbva[0] );
1938         }
1939
1940         if ( mlnext->sml_next ) {
1941                 slap_mods_free( mlnext->sml_next );
1942                 mlnext->sml_next = NULL;
1943         }
1944
1945         for (ml = modlist ; ml != NULL; ml = mlnext ) {
1946                 mlnext = ml->sml_next;
1947                 free( ml );
1948         }
1949
1950         return;
1951 }
1952
1953 int
1954 syncrepl_isupdate( Operation *op )
1955 {
1956         return ( syncrepl_isupdate_dn( op->o_bd, &op->o_ndn ));
1957 }
1958
1959 int
1960 syncrepl_isupdate_dn(
1961         Backend*                be,
1962         struct berval*  ndn )
1963 {
1964         syncinfo_t*     si;
1965         int                     ret = 0;
1966
1967         if ( !LDAP_STAILQ_EMPTY( &be->be_syncinfo )) {
1968                 LDAP_STAILQ_FOREACH( si, &be->be_syncinfo, si_next ) {
1969                         if ( ( ret = dn_match( &si->si_updatedn, ndn ) ) ) {
1970                                 return ret;
1971                         }
1972                 }
1973         }
1974         return 0;
1975 }
1976
1977 static int
1978 dn_callback(
1979         Operation*      op,
1980         SlapReply*      rs )
1981 {
1982         syncinfo_t *si = op->o_callback->sc_private;
1983
1984         if ( rs->sr_type == REP_SEARCH ) {
1985                 if ( !BER_BVISNULL( &si->si_syncUUID_ndn ) ) {
1986                         Debug( LDAP_DEBUG_ANY,
1987                                 "dn_callback : consistency error - "
1988                                 "entryUUID is not unique\n", 0, 0, 0 );
1989                 } else {
1990                         ber_dupbv_x( &si->si_syncUUID_ndn, &rs->sr_entry->e_nname, NULL );
1991                 }
1992         } else if ( rs->sr_type == REP_RESULT ) {
1993                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
1994                         Debug( LDAP_DEBUG_ANY,
1995                                 "dn_callback : consistency error - "
1996                                 "entryUUID is not unique\n", 0, 0, 0 );
1997                 }
1998         }
1999
2000         return LDAP_SUCCESS;
2001 }
2002
2003 static int
2004 nonpresent_callback(
2005         Operation*      op,
2006         SlapReply*      rs )
2007 {
2008         syncinfo_t *si = op->o_callback->sc_private;
2009         Attribute *a;
2010         int count = 0;
2011         struct berval* present_uuid = NULL;
2012         struct nonpresent_entry *np_entry;
2013
2014         if ( rs->sr_type == REP_RESULT ) {
2015                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2016                 si->si_presentlist = NULL;
2017
2018         } else if ( rs->sr_type == REP_SEARCH ) {
2019                 a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2020
2021                 if ( a == NULL ) return 0;
2022
2023                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2024                         syncuuid_cmp );
2025
2026                 if ( present_uuid == NULL ) {
2027                         np_entry = (struct nonpresent_entry *)
2028                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2029                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2030                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2031                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2032
2033                 } else {
2034                         avl_delete( &si->si_presentlist,
2035                                         &a->a_nvals[0], syncuuid_cmp );
2036                         ch_free( present_uuid->bv_val );
2037                         ch_free( present_uuid );
2038                 }
2039         }
2040         return LDAP_SUCCESS;
2041 }
2042
2043 static int
2044 null_callback(
2045         Operation*      op,
2046         SlapReply*      rs )
2047 {
2048         if ( rs->sr_err != LDAP_SUCCESS &&
2049                 rs->sr_err != LDAP_REFERRAL &&
2050                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2051                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2052                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2053         {
2054                 Debug( LDAP_DEBUG_ANY,
2055                         "null_callback : error code 0x%x\n",
2056                         rs->sr_err, 0, 0 );
2057         }
2058         return LDAP_SUCCESS;
2059 }
2060
2061 Entry *
2062 slap_create_syncrepl_entry(
2063         Backend *be,
2064         struct berval *context_csn,
2065         struct berval *rdn,
2066         struct berval *cn )
2067 {
2068         Entry* e;
2069
2070         struct berval bv;
2071
2072         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ));
2073
2074         attr_merge( e, slap_schema.si_ad_objectClass, ocbva, NULL );
2075
2076         attr_merge_one( e, slap_schema.si_ad_structuralObjectClass,
2077                 &ocbva[1], NULL );
2078
2079         attr_merge_one( e, slap_schema.si_ad_cn, cn, NULL );
2080
2081         if ( context_csn ) {
2082                 attr_merge_one( e, slap_schema.si_ad_syncreplCookie,
2083                         context_csn, NULL );
2084         }
2085
2086         BER_BVSTR( &bv, "{}" );
2087         attr_merge_one( e, slap_schema.si_ad_subtreeSpecification, &bv, NULL );
2088
2089         build_new_dn( &e->e_name, &be->be_nsuffix[0], rdn, NULL );
2090         ber_dupbv( &e->e_nname, &e->e_name );
2091
2092         return e;
2093 }
2094
2095 struct berval *
2096 slap_uuidstr_from_normalized(
2097         struct berval* uuidstr,
2098         struct berval* normalized,
2099         void *ctx )
2100 {
2101         struct berval *new;
2102         unsigned char nibble;
2103         int i, d = 0;
2104
2105         if ( normalized == NULL ) return NULL;
2106         if ( normalized->bv_len != 16 ) return NULL;
2107
2108         if ( uuidstr ) {
2109                 new = uuidstr;
2110         } else {
2111                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2112                 if ( new == NULL ) {
2113                         return NULL;
2114                 }
2115         }
2116
2117         new->bv_len = 36;
2118
2119         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2120                 if ( new != uuidstr ) {
2121                         slap_sl_free( new, ctx );
2122                 }
2123                 return NULL;
2124         }
2125
2126         for ( i = 0; i < 16; i++ ) {
2127                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2128                         new->bv_val[(i<<1)+d] = '-';
2129                         d += 1;
2130                 }
2131
2132                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2133                 if ( nibble < 10 ) {
2134                         new->bv_val[(i<<1)+d] = nibble + '0';
2135                 } else {
2136                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2137                 }
2138
2139                 nibble = (normalized->bv_val[i]) & 0xF;
2140                 if ( nibble < 10 ) {
2141                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2142                 } else {
2143                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2144                 }
2145         }
2146
2147         new->bv_val[new->bv_len] = '\0';
2148         return new;
2149 }
2150
2151 static int
2152 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2153 {
2154         const struct berval *uuid1 = v_uuid1;
2155         const struct berval *uuid2 = v_uuid2;
2156         int rc = uuid1->bv_len - uuid2->bv_len;
2157         if ( rc ) return rc;
2158         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2159 }
2160
2161 static void
2162 avl_ber_bvfree( void *v_bv )
2163 {
2164         struct berval   *bv = (struct berval *)v_bv;
2165         
2166         if( v_bv == NULL ) return;
2167         if ( !BER_BVISNULL( bv ) ) {
2168                 ch_free( bv->bv_val );
2169         }
2170         ch_free( (char *) bv );
2171 }
2172
2173 void
2174 syncinfo_free( syncinfo_t *sie )
2175 {
2176         if ( sie->si_provideruri ) {
2177                 ch_free( sie->si_provideruri );
2178         }
2179         if ( sie->si_provideruri_bv ) {
2180                 ber_bvarray_free( sie->si_provideruri_bv );
2181         }
2182         if ( sie->si_updatedn.bv_val ) {
2183                 ch_free( sie->si_updatedn.bv_val );
2184         }
2185         if ( sie->si_binddn ) {
2186                 ch_free( sie->si_binddn );
2187         }
2188         if ( sie->si_passwd ) {
2189                 ch_free( sie->si_passwd );
2190         }
2191         if ( sie->si_saslmech ) {
2192                 ch_free( sie->si_saslmech );
2193         }
2194         if ( sie->si_secprops ) {
2195                 ch_free( sie->si_secprops );
2196         }
2197         if ( sie->si_realm ) {
2198                 ch_free( sie->si_realm );
2199         }
2200         if ( sie->si_authcId ) {
2201                 ch_free( sie->si_authcId );
2202         }
2203         if ( sie->si_authzId ) {
2204                 ch_free( sie->si_authzId );
2205         }
2206         if ( sie->si_filterstr.bv_val ) {
2207                 ch_free( sie->si_filterstr.bv_val );
2208         }
2209         if ( sie->si_base.bv_val ) {
2210                 ch_free( sie->si_base.bv_val );
2211         }
2212         if ( sie->si_attrs ) {
2213                 int i = 0;
2214                 while ( sie->si_attrs[i] != NULL ) {
2215                         ch_free( sie->si_attrs[i] );
2216                         i++;
2217                 }
2218                 ch_free( sie->si_attrs );
2219         }
2220         if ( sie->si_exattrs ) {
2221                 int i = 0;
2222                 while ( sie->si_exattrs[i] != NULL ) {
2223                         ch_free( sie->si_exattrs[i] );
2224                         i++;
2225                 }
2226                 ch_free( sie->si_exattrs );
2227         }
2228         if ( sie->si_anlist ) {
2229                 int i = 0;
2230                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2231                         ch_free( sie->si_anlist[i].an_name.bv_val );
2232                         i++;
2233                 }
2234                 ch_free( sie->si_anlist );
2235         }
2236         if ( sie->si_exanlist ) {
2237                 int i = 0;
2238                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2239                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2240                         i++;
2241                 }
2242                 ch_free( sie->si_exanlist );
2243         }
2244         if ( sie->si_retryinterval ) {
2245                 ch_free( sie->si_retryinterval );
2246         }
2247         if ( sie->si_retrynum ) {
2248                 ch_free( sie->si_retrynum );
2249         }
2250         if ( sie->si_retrynum_init ) {
2251                 ch_free( sie->si_retrynum_init );
2252         }
2253         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2254         if ( sie->si_syncUUID_ndn.bv_val ) {
2255                 ch_free( sie->si_syncUUID_ndn.bv_val );
2256         }
2257         if ( sie->si_presentlist ) {
2258             avl_free( sie->si_presentlist, avl_ber_bvfree );
2259         }
2260         if ( sie->si_ld ) {
2261                 ldap_ld_free( sie->si_ld, 1, NULL, NULL );
2262         }
2263         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2264                 struct nonpresent_entry* npe;
2265                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2266                 LDAP_LIST_REMOVE( npe, npe_link );
2267                 if ( npe->npe_name ) {
2268                         if ( npe->npe_name->bv_val ) {
2269                                 ch_free( npe->npe_name->bv_val );
2270                         }
2271                         ch_free( npe->npe_name );
2272                 }
2273                 if ( npe->npe_nname ) {
2274                         if ( npe->npe_nname->bv_val ) {
2275                                 ch_free( npe->npe_nname->bv_val );
2276                         }
2277                         ch_free( npe->npe_nname );
2278                 }
2279                 ch_free( npe );
2280         }
2281         ch_free( sie );
2282 }