]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
a2c707a4ed957600136a57c82a6426b70ee7a672
[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-2005 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 "config.h"
31
32 #include "ldap_rq.h"
33
34 /* FIXME: for ldap_ld_free() */
35 #undef ldap_debug
36 #include "../../libraries/libldap/ldap-int.h"
37
38 struct nonpresent_entry {
39         struct berval *npe_name;
40         struct berval *npe_nname;
41         LDAP_LIST_ENTRY(nonpresent_entry) npe_link;
42 };
43
44 typedef struct syncinfo_s {
45         struct slap_backend_db *si_be;
46         struct re_s                     *si_re;
47         long                            si_rid;
48         struct berval           si_provideruri;
49         slap_bindconf           si_bindconf;
50         struct berval           si_filterstr;
51         struct berval           si_base;
52         int                                     si_scope;
53         int                                     si_attrsonly;
54         char                            *si_anfile;
55         AttributeName           *si_anlist;
56         AttributeName           *si_exanlist;
57         char                            **si_attrs;
58         char                            **si_exattrs;
59         int                                     si_allattrs;
60         int                                     si_allopattrs;
61         int                                     si_schemachecking;
62         int                                     si_type;
63         time_t                          si_interval;
64         time_t                          *si_retryinterval;
65         int                                     *si_retrynum_init;
66         int                                     *si_retrynum;
67         struct sync_cookie      si_syncCookie;
68         int                                     si_manageDSAit;
69         int                                     si_slimit;
70         int                                     si_tlimit;
71         int                                     si_refreshDelete;
72         int                                     si_refreshPresent;
73         Avlnode                         *si_presentlist;
74         LDAP                            *si_ld;
75         LDAP_LIST_HEAD(np, nonpresent_entry) si_nonpresentlist;
76         ldap_pvt_thread_mutex_t si_mutex;
77 } syncinfo_t;
78
79 static int syncuuid_cmp( const void *, const void * );
80 static void avl_ber_bvfree( void * );
81 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray );
82 static int syncrepl_message_to_entry(
83                                         syncinfo_t *, Operation *, LDAPMessage *,
84                                         Modifications **, Entry **, int );
85 static int syncrepl_entry(
86                                         syncinfo_t *, Operation*, Entry*,
87                                         Modifications**,int, struct berval*,
88                                         struct sync_cookie *,
89                                         struct berval * );
90 static void syncrepl_updateCookie(
91                                         syncinfo_t *, Operation *, struct berval *,
92                                         struct sync_cookie * );
93 static struct berval * slap_uuidstr_from_normalized(
94                                         struct berval *, struct berval *, void * );
95
96 /* callback functions */
97 static int dn_callback( struct slap_op *, struct slap_rep * );
98 static int nonpresent_callback( struct slap_op *, struct slap_rep * );
99 static int null_callback( struct slap_op *, struct slap_rep * );
100
101 static AttributeDescription *sync_descs[4];
102
103 static void
104 init_syncrepl(syncinfo_t *si)
105 {
106         int i, j, k, l, n;
107         char **attrs, **exattrs;
108
109         if ( !sync_descs[0] ) {
110                 sync_descs[0] = slap_schema.si_ad_objectClass;
111                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
112                 sync_descs[2] = slap_schema.si_ad_entryCSN;
113                 sync_descs[3] = NULL;
114         }
115
116         if ( si->si_allattrs && si->si_allopattrs )
117                 attrs = NULL;
118         else
119                 attrs = anlist2attrs( si->si_anlist );
120
121         if ( attrs ) {
122                 if ( si->si_allattrs ) {
123                         i = 0;
124                         while ( attrs[i] ) {
125                                 if ( !is_at_operational( at_find( attrs[i] ))) {
126                                         for ( j = i; attrs[j] != NULL; j++ ) {
127                                                 if ( j == i )
128                                                         ch_free( attrs[i] );
129                                                 attrs[j] = attrs[j+1];
130                                         }
131                                 } else {
132                                         i++;
133                                 }
134                         }
135                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
136                         attrs[i] = ch_strdup("*");
137                         attrs[i + 1] = NULL;
138
139                 } else if ( si->si_allopattrs ) {
140                         i = 0;
141                         while ( attrs[i] ) {
142                                 if ( is_at_operational( at_find( attrs[i] ))) {
143                                         for ( j = i; attrs[j] != NULL; j++ ) {
144                                                 if ( j == i )
145                                                         ch_free( attrs[i] );
146                                                 attrs[j] = attrs[j+1];
147                                         }
148                                 } else {
149                                         i++;
150                                 }
151                         }
152                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
153                         attrs[i] = ch_strdup("+");
154                         attrs[i + 1] = NULL;
155                 }
156
157                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
158                         j = 0;
159                         while ( attrs[j] ) {
160                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val )) {
161                                         for ( k = j; attrs[k] != NULL; k++ ) {
162                                                 if ( k == j )
163                                                         ch_free( attrs[k] );
164                                                 attrs[k] = attrs[k+1];
165                                         }
166                                 } else {
167                                         j++;
168                                 }
169                         }
170                 }
171
172                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
173
174                 if ( si->si_allopattrs ) {
175                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ));
176                 } else {
177                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ));
178                 }
179
180                 if ( attrs == NULL ) {
181                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0,0,0 );
182                 }
183
184                 /* Add Attributes */
185                 if ( si->si_allopattrs ) {
186                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
187                 } else {
188                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
189                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
190                         }
191                 }
192                 attrs[ n ] = NULL;
193
194         } else {
195
196                 i = 0;
197                 if ( si->si_allattrs == si->si_allopattrs ) {
198                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
199                         attrs[i++] = ch_strdup( "*" );
200                         attrs[i++] = ch_strdup( "+" );
201                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
202                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
203                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
204                         attrs[i++] = ch_strdup( "*" );
205                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
206                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
207                         }
208                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
209                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
210                         attrs[i++] = ch_strdup( "+" );
211                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
212                 }
213                 attrs[i] = NULL;
214         }
215         
216         si->si_attrs = attrs;
217
218         exattrs = anlist2attrs( si->si_exanlist );
219
220         if ( exattrs ) {
221                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
222
223                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
224                         j = 0;
225                         while ( exattrs[j] != NULL ) {
226                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val )) {
227                                         for ( k = j; exattrs[k] != NULL; k++ ) {
228                                                 if ( k == j )
229                                                         ch_free( exattrs[k] );
230                                                 exattrs[k] = exattrs[k+1];
231                                         }
232                                 } else {
233                                         j++;
234                                 }
235                         }
236                 }
237
238                 for ( i = 0; exattrs[i] != NULL; i++ ) {
239                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
240                                 ObjectClass     *oc;
241                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
242                                         k = 0;
243                                         while ( oc->soc_required[k] ) {
244                                                 if ( !strcmp( exattrs[i],
245                                                          oc->soc_required[k]->sat_cname.bv_val )) {
246                                                         for ( l = i; exattrs[l]; l++ ) {
247                                                                 if ( l == i )
248                                                                         ch_free( exattrs[i] );
249                                                                 exattrs[l] = exattrs[l+1];
250                                                         }
251                                                 } else {
252                                                         k++;
253                                                 }
254                                         }
255                                 }
256                         }
257                 }
258
259                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
260
261                 if ( i != n )
262                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *));
263         }
264
265         si->si_exattrs = exattrs;       
266 }
267
268 static int
269 ldap_sync_search(
270         syncinfo_t *si,
271         void *ctx )
272 {
273         BerElementBuffer berbuf;
274         BerElement *ber = (BerElement *)&berbuf;
275         LDAPControl c[2], *ctrls[3];
276         struct timeval timeout;
277         ber_int_t       msgid;
278         int rc;
279
280         /* setup LDAP SYNC control */
281         ber_init2( ber, NULL, LBER_USE_DER );
282         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
283
284         if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
285         {
286                 ber_printf( ber, "{eO}",
287                         abs(si->si_type),
288                         &si->si_syncCookie.octet_str );
289         } else {
290                 ber_printf( ber, "{e}",
291                         abs(si->si_type) );
292         }
293
294         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 )) == LBER_ERROR ) {
295                 ber_free_buf( ber );
296                 return rc;
297         }
298
299         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
300         c[0].ldctl_iscritical = si->si_type < 0;
301         ctrls[0] = &c[0];
302
303         if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
304                 c[1].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
305                 c[1].ldctl_value = si->si_bindconf.sb_authzId;
306                 c[1].ldctl_iscritical = 1;
307                 ctrls[1] = &c[1];
308                 ctrls[2] = NULL;
309         } else {
310                 ctrls[1] = NULL;
311         }
312
313         timeout.tv_sec = si->si_tlimit;
314         timeout.tv_usec = 0;
315
316         rc = ldap_search_ext( si->si_ld, si->si_base.bv_val, si->si_scope,
317                 si->si_filterstr.bv_val, si->si_attrs, si->si_attrsonly,
318                 ctrls, NULL, si->si_tlimit > 0 ? &timeout : NULL,
319                 si->si_slimit, &msgid );
320         ber_free_buf( ber );
321         return rc;
322 }
323
324 static int
325 do_syncrep1(
326         Operation *op,
327         syncinfo_t *si )
328 {
329         int     rc;
330         int cmdline_cookie_found = 0;
331
332         struct sync_cookie      *sc = NULL;
333         struct berval   *psub;
334 #ifdef HAVE_TLS
335         void    *ssl;
336 #endif
337
338         psub = &si->si_be->be_nsuffix[0];
339
340         /* Init connection to master */
341         rc = ldap_initialize( &si->si_ld, si->si_provideruri.bv_val );
342         if ( rc != LDAP_SUCCESS ) {
343                 Debug( LDAP_DEBUG_ANY,
344                         "do_syncrep1: ldap_initialize failed (%s)\n",
345                         si->si_provideruri.bv_val, 0, 0 );
346                 return rc;
347         }
348
349         op->o_protocol = LDAP_VERSION3;
350         ldap_set_option( si->si_ld, LDAP_OPT_PROTOCOL_VERSION, &op->o_protocol );
351
352         /* Bind to master */
353
354         if ( si->si_bindconf.sb_tls ) {
355                 rc = ldap_start_tls_s( si->si_ld, NULL, NULL );
356                 if( rc != LDAP_SUCCESS ) {
357                         Debug( LDAP_DEBUG_ANY,
358                                 "%s: ldap_start_tls failed (%d)\n",
359                                 si->si_bindconf.sb_tls == SB_TLS_CRITICAL ? "Error" : "Warning",
360                                 rc, 0 );
361                         if( si->si_bindconf.sb_tls == SB_TLS_CRITICAL ) goto done;
362                 }
363         }
364
365         if ( si->si_bindconf.sb_method == LDAP_AUTH_SASL ) {
366 #ifdef HAVE_CYRUS_SASL
367                 void *defaults;
368
369                 if ( si->si_bindconf.sb_secprops != NULL ) {
370                         rc = ldap_set_option( si->si_ld,
371                                 LDAP_OPT_X_SASL_SECPROPS, si->si_bindconf.sb_secprops);
372
373                         if( rc != LDAP_OPT_SUCCESS ) {
374                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
375                                         "(%s,SECPROPS,\"%s\") failed!\n",
376                                         si->si_provideruri.bv_val, si->si_bindconf.sb_secprops, 0 );
377                                 goto done;
378                         }
379                 }
380
381                 defaults = lutil_sasl_defaults( si->si_ld,
382                         si->si_bindconf.sb_saslmech.bv_val,
383                         si->si_bindconf.sb_realm.bv_val,
384                         si->si_bindconf.sb_authcId.bv_val,
385                         si->si_bindconf.sb_cred.bv_val,
386                         si->si_bindconf.sb_authzId.bv_val );
387
388                 rc = ldap_sasl_interactive_bind_s( si->si_ld,
389                                 si->si_bindconf.sb_binddn.bv_val,
390                                 si->si_bindconf.sb_saslmech.bv_val,
391                                 NULL, NULL,
392                                 LDAP_SASL_QUIET,
393                                 lutil_sasl_interact,
394                                 defaults );
395
396                 lutil_sasl_freedefs( defaults );
397
398                 /* FIXME: different error behaviors according to
399                  *      1) return code
400                  *      2) on err policy : exit, retry, backoff ...
401                  */
402                 if ( rc != LDAP_SUCCESS ) {
403                         static struct berval bv_GSSAPI = BER_BVC( "GSSAPI" );
404
405                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
406                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
407                                 rc, 0, 0 );
408
409                         /* FIXME (see above comment) */
410                         /* if Kerberos credentials cache is not active, retry */
411                         if ( ber_bvcmp( &si->si_bindconf.sb_saslmech, &bv_GSSAPI ) == 0 &&
412                                 rc == LDAP_LOCAL_ERROR )
413                         {
414                                 rc = LDAP_SERVER_DOWN;
415                         }
416
417                         goto done;
418                 }
419 #else /* HAVE_CYRUS_SASL */
420                 /* Should never get here, we trapped this at config time */
421                 assert(0);
422                 fprintf( stderr, "not compiled with SASL support\n" );
423                 rc = LDAP_OTHER;
424                 goto done;
425 #endif
426
427         } else if ( si->si_bindconf.sb_method == LDAP_AUTH_SIMPLE ) {
428                 rc = ldap_sasl_bind_s( si->si_ld,
429                         si->si_bindconf.sb_binddn.bv_val, LDAP_SASL_SIMPLE,
430                         &si->si_bindconf.sb_cred, NULL, NULL, NULL );
431                 if ( rc != LDAP_SUCCESS ) {
432                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
433                                 "ldap_sasl_bind_s failed (%d)\n", rc, 0, 0 );
434                         goto done;
435                 }
436         }
437
438         /* Set SSF to strongest of TLS, SASL SSFs */
439         op->o_sasl_ssf = 0;
440         op->o_tls_ssf = 0;
441         op->o_transport_ssf = 0;
442 #ifdef HAVE_TLS
443         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
444                 == LDAP_SUCCESS && ssl != NULL )
445         {
446                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
447         }
448 #endif /* HAVE_TLS */
449         ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &op->o_sasl_ssf );
450         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
451                 ?  op->o_sasl_ssf : op->o_tls_ssf;
452
453
454         if ( BER_BVISNULL( &si->si_syncCookie.octet_str )) {
455                 /* get contextCSN shadow replica from database */
456                 BerVarray csn = NULL;
457
458                 assert( si->si_rid < 1000 );
459                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
460                 op->o_req_dn = op->o_req_ndn;
461
462                 /* try to read stored contextCSN */
463                 backend_attribute( op, NULL, &op->o_req_ndn,
464                         slap_schema.si_ad_contextCSN, &csn, ACL_READ );
465                 if ( csn ) {
466                         ch_free( si->si_syncCookie.ctxcsn.bv_val );
467                         ber_dupbv( &si->si_syncCookie.ctxcsn, csn );
468                         ber_bvarray_free_x( csn, op->o_tmpmemctx );
469                 }
470
471                 si->si_syncCookie.rid = si->si_rid;
472
473                 LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
474                         if ( si->si_rid == sc->rid ) {
475                                 cmdline_cookie_found = 1;
476                                 break;
477                         }
478                 }
479
480                 if ( cmdline_cookie_found ) {
481                         /* cookie is supplied in the command line */
482
483                         LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
484
485                         /* ctxcsn wasn't parsed yet, do it now */
486                         slap_parse_sync_cookie( sc, op->o_tmpmemctx );
487                         if ( BER_BVISNULL( &sc->ctxcsn ) ) {
488                                 /* if cmdline cookie does not have ctxcsn */
489                                 /* component, set it to an initial value */
490                                 slap_init_sync_cookie_ctxcsn( sc );
491                         }
492                         slap_sync_cookie_free( &si->si_syncCookie, 0 );
493                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
494                         slap_sync_cookie_free( sc, 1 );
495                 }
496
497                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
498                         &si->si_syncCookie.ctxcsn, si->si_syncCookie.rid );
499         }
500
501         rc = ldap_sync_search( si, op->o_tmpmemctx );
502
503         if( rc != LDAP_SUCCESS ) {
504                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
505                         "ldap_search_ext: %s (%d)\n", ldap_err2string( rc ), rc, 0 );
506         }
507
508 done:
509         if ( rc ) {
510                 if ( si->si_ld ) {
511                         ldap_unbind_ext( si->si_ld, NULL, NULL );
512                         si->si_ld = NULL;
513                 }
514         }
515
516         return rc;
517 }
518
519 static int
520 do_syncrep2(
521         Operation *op,
522         syncinfo_t *si )
523 {
524         LDAPControl     **rctrls = NULL;
525         LDAPControl     *rctrlp;
526
527         BerElementBuffer berbuf;
528         BerElement      *ber = (BerElement *)&berbuf;
529
530         LDAPMessage     *res = NULL;
531         LDAPMessage     *msg = NULL;
532
533         char            *retoid = NULL;
534         struct berval   *retdata = NULL;
535
536         Entry           *entry = NULL;
537
538         int             syncstate;
539         struct berval   syncUUID = BER_BVNULL;
540         struct sync_cookie      syncCookie = { BER_BVNULL };
541         struct sync_cookie      syncCookie_req = { BER_BVNULL };
542         struct berval           cookie = BER_BVNULL;
543
544         int     rc, err, i;
545         ber_len_t       len;
546
547         int rc_efree = 1;
548
549         struct berval   *psub;
550         Modifications   *modlist = NULL;
551
552         const char              *text;
553         int                             match;
554
555         struct timeval *tout_p = NULL;
556         struct timeval tout = { 0, 0 };
557
558         int             refreshDeletes = 0;
559         int             refreshDone = 1;
560         BerVarray syncUUIDs = NULL;
561         ber_tag_t si_tag;
562
563         if ( slapd_shutdown ) {
564                 rc = -2;
565                 goto done;
566         }
567
568         ber_init2( ber, NULL, LBER_USE_DER );
569         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
570
571         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2\n", 0, 0, 0 );
572
573         psub = &si->si_be->be_nsuffix[0];
574
575         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
576
577         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
578                 tout_p = &tout;
579         } else {
580                 tout_p = NULL;
581         }
582
583         while (( rc = ldap_result( si->si_ld, LDAP_RES_ANY, LDAP_MSG_ONE,
584                 tout_p, &res )) > 0 )
585         {
586                 if ( slapd_shutdown ) {
587                         rc = -2;
588                         goto done;
589                 }
590                 for( msg = ldap_first_message( si->si_ld, res );
591                         msg != NULL;
592                         msg = ldap_next_message( si->si_ld, msg ) )
593                 {
594                         if ( slapd_shutdown ) {
595                                 rc = -2;
596                                 goto done;
597                         }
598                         switch( ldap_msgtype( msg ) ) {
599                         case LDAP_RES_SEARCH_ENTRY:
600                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
601                                 /* we can't work without the control */
602                                 if ( !rctrls ) {
603                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: "
604                                                 "got search entry without "
605                                                 "control\n", 0, 0, 0 );
606                                         rc = -1;
607                                         goto done;
608                                 }
609                                 rctrlp = *rctrls;
610                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
611                                 ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
612                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
613                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
614                                         if ( !BER_BVISNULL( &cookie ) ) {
615                                                 ch_free( syncCookie.octet_str.bv_val );
616                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
617                                         }
618                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
619                                         {
620                                                 slap_parse_sync_cookie( &syncCookie, NULL );
621                                         }
622                                 }
623                                 if ( syncrepl_message_to_entry( si, op, msg,
624                                         &modlist, &entry, syncstate ) == LDAP_SUCCESS ) {
625                                         rc_efree = syncrepl_entry( si, op, entry, &modlist,
626                                                 syncstate, &syncUUID, &syncCookie_req, &syncCookie.ctxcsn );
627                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
628                                         {
629                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
630                                         }
631                                 }
632                                 ldap_controls_free( rctrls );
633                                 if ( modlist ) {
634                                         slap_mods_free( modlist, 1 );
635                                 }
636                                 if ( rc_efree && entry ) {
637                                         entry_free( entry );
638                                 }
639                                 entry = NULL;
640                                 break;
641
642                         case LDAP_RES_SEARCH_REFERENCE:
643                                 Debug( LDAP_DEBUG_ANY,
644                                         "do_syncrep2: reference received error\n", 0, 0, 0 );
645                                 break;
646
647                         case LDAP_RES_SEARCH_RESULT:
648                                 Debug( LDAP_DEBUG_SYNC,
649                                         "do_syncrep2: LDAP_RES_SEARCH_RESULT\n", 0, 0, 0 );
650                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
651                                         &rctrls, 0 );
652                                 if ( rctrls ) {
653                                         rctrlp = *rctrls;
654                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
655
656                                         ber_scanf( ber, "{" /*"}"*/);
657                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
658                                                 ber_scanf( ber, "m", &cookie );
659                                                 if ( !BER_BVISNULL( &cookie ) ) {
660                                                         ch_free( syncCookie.octet_str.bv_val );
661                                                         ber_dupbv( &syncCookie.octet_str, &cookie);
662                                                 }
663                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
664                                                 {
665                                                         slap_parse_sync_cookie( &syncCookie, NULL );
666                                                 }
667                                         }
668                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
669                                         {
670                                                 ber_scanf( ber, "b", &refreshDeletes );
671                                         }
672                                         ber_scanf( ber, /*"{"*/ "}" );
673                                 }
674                                 if ( BER_BVISNULL( &syncCookie_req.ctxcsn )) {
675                                         match = -1;
676                                 } else if ( BER_BVISNULL( &syncCookie.ctxcsn )) {
677                                         match = 1;
678                                 } else {
679                                         value_match( &match, slap_schema.si_ad_entryCSN,
680                                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
681                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
682                                                 &syncCookie_req.ctxcsn, &syncCookie.ctxcsn,
683                                                 &text );
684                                 }
685                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) &&
686                                         match < 0 && err == LDAP_SUCCESS )
687                                 {
688                                         syncrepl_updateCookie( si, op, psub, &syncCookie );
689                                 }
690                                 if ( rctrls ) {
691                                         ldap_controls_free( rctrls );
692                                 }
693                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
694                                         /* FIXME : different error behaviors according to
695                                          *      1) err code : LDAP_BUSY ...
696                                          *      2) on err policy : stop service, stop sync, retry
697                                          */
698                                         if ( refreshDeletes == 0 && match < 0 &&
699                                                 err == LDAP_SUCCESS )
700                                         {
701                                                 syncrepl_del_nonpresent( op, si, NULL );
702                                         } else {
703                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
704                                                 si->si_presentlist = NULL;
705                                         }
706                                 }
707                                 rc = -2;
708                                 goto done;
709                                 break;
710
711                         case LDAP_RES_INTERMEDIATE:
712                                 rc = ldap_parse_intermediate( si->si_ld, msg,
713                                         &retoid, &retdata, NULL, 0 );
714                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
715                                         ber_init2( ber, retdata, LBER_USE_DER );
716
717                                         switch ( si_tag = ber_peek_tag( ber, &len )) {
718                                         ber_tag_t tag;
719                                         case LDAP_TAG_SYNC_NEW_COOKIE:
720                                                 Debug( LDAP_DEBUG_SYNC,
721                                                         "do_syncrep2: %s - %s%s\n", 
722                                                         "LDAP_RES_INTERMEDIATE", 
723                                                         "NEW_COOKIE", "\n" );
724                                                 ber_scanf( ber, "tm", &tag, &cookie );
725                                                 break;
726                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
727                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
728                                                 Debug( LDAP_DEBUG_SYNC,
729                                                         "do_syncrep2: %s - %s%s\n", 
730                                                         "LDAP_RES_INTERMEDIATE", 
731                                                         si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
732                                                         "REFRESH_PRESENT" : "REFRESH_DELETE",
733                                                         "\n" );
734                                                 if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
735                                                         si->si_refreshDelete = 1;
736                                                 } else {
737                                                         si->si_refreshPresent = 1;
738                                                 }
739                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
740                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
741                                                 {
742                                                         ber_scanf( ber, "m", &cookie );
743                                                         if ( !BER_BVISNULL( &cookie ) ) {
744                                                                 ch_free( syncCookie.octet_str.bv_val );
745                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
746                                                         }
747                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
748                                                         {
749                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
750                                                         }
751                                                 }
752                                                 if ( ber_peek_tag( ber, &len ) ==
753                                                         LDAP_TAG_REFRESHDONE )
754                                                 {
755                                                         ber_scanf( ber, "b", &refreshDone );
756                                                 }
757                                                 ber_scanf( ber, /*"{"*/ "}" );
758                                                 break;
759                                         case LDAP_TAG_SYNC_ID_SET:
760                                                 Debug( LDAP_DEBUG_SYNC,
761                                                         "do_syncrep2: %s - %s%s\n", 
762                                                         "LDAP_RES_INTERMEDIATE", 
763                                                         "SYNC_ID_SET",
764                                                         "\n" );
765                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
766                                                 if ( ber_peek_tag( ber, &len ) ==
767                                                         LDAP_TAG_SYNC_COOKIE )
768                                                 {
769                                                         ber_scanf( ber, "m", &cookie );
770                                                         if ( !BER_BVISNULL( &cookie ) ) {
771                                                                 ch_free( syncCookie.octet_str.bv_val );
772                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
773                                                         }
774                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
775                                                         {
776                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
777                                                         }
778                                                 }
779                                                 if ( ber_peek_tag( ber, &len ) ==
780                                                         LDAP_TAG_REFRESHDELETES )
781                                                 {
782                                                         ber_scanf( ber, "b", &refreshDeletes );
783                                                 }
784                                                 ber_scanf( ber, "[W]", &syncUUIDs );
785                                                 ber_scanf( ber, /*"{"*/ "}" );
786                                                 if ( refreshDeletes ) {
787                                                         syncrepl_del_nonpresent( op, si, syncUUIDs );
788                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
789                                                 } else {
790                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
791                                                                 struct berval *syncuuid_bv;
792                                                                 syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
793                                                                 slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
794                                                                 avl_insert( &si->si_presentlist,
795                                                                         (caddr_t) syncuuid_bv,
796                                                                         syncuuid_cmp, avl_dup_error );
797                                                         }
798                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
799                                                 }
800                                                 break;
801                                         default:
802                                                 Debug( LDAP_DEBUG_ANY,
803                                                         "do_syncrep2 : unknown syncinfo tag (%ld)\n",
804                                                 (long) si_tag, 0, 0 );
805                                                 ldap_memfree( retoid );
806                                                 ber_bvfree( retdata );
807                                                 continue;
808                                         }
809
810                                         if ( BER_BVISNULL( &syncCookie_req.ctxcsn )) {
811                                                 match = -1;
812                                         } else if ( BER_BVISNULL( &syncCookie.ctxcsn )) {
813                                                 match = 1;
814                                         } else {
815                                                 value_match( &match, slap_schema.si_ad_entryCSN,
816                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
817                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
818                                                         &syncCookie_req.ctxcsn,
819                                                         &syncCookie.ctxcsn, &text );
820                                         }
821
822                                         if ( !BER_BVISNULL( &syncCookie.ctxcsn ) &&
823                                                 match < 0 )
824                                         {
825                                                 syncrepl_updateCookie( si, op, psub, &syncCookie);
826                                         }
827
828                                         if ( si->si_refreshPresent == 1 ) {
829                                                 if ( match < 0 ) {
830                                                         syncrepl_del_nonpresent( op, si, NULL );
831                                                 }
832                                         } 
833
834                                         ldap_memfree( retoid );
835                                         ber_bvfree( retdata );
836                                         break;
837
838                                 } else {
839                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
840                                                 "unknown intermediate response (%d)\n",
841                                                 rc, 0, 0 );
842                                         ldap_memfree( retoid );
843                                         ber_bvfree( retdata );
844                                         break;
845                                 }
846                                 break;
847
848                         default:
849                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
850                                         "unknown message\n", 0, 0, 0 );
851                                 break;
852
853                         }
854                         if ( !BER_BVISNULL( &syncCookie.octet_str )) {
855                                 slap_sync_cookie_free( &syncCookie_req, 0 );
856                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
857                                 slap_sync_cookie_free( &syncCookie, 0 );
858                         }
859                 }
860                 ldap_msgfree( res );
861                 res = NULL;
862         }
863
864         if ( rc == -1 ) {
865                 const char *errstr;
866
867                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
868                 errstr = ldap_err2string( rc );
869                 
870                 Debug( LDAP_DEBUG_ANY,
871                         "do_syncrep2 : %s\n", errstr, 0, 0 );
872         }
873
874 done:
875         slap_sync_cookie_free( &syncCookie, 0 );
876         slap_sync_cookie_free( &syncCookie_req, 0 );
877
878         if ( res ) ldap_msgfree( res );
879
880         if ( rc && si->si_ld ) {
881                 ldap_unbind_ext( si->si_ld, NULL, NULL );
882                 si->si_ld = NULL;
883         }
884
885         return rc;
886 }
887
888 static void *
889 do_syncrepl(
890         void    *ctx,
891         void    *arg )
892 {
893         struct re_s* rtask = arg;
894         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
895         Connection conn = {0};
896         char opbuf[OPERATION_BUFFER_SIZE];
897         Operation *op;
898         int rc = LDAP_SUCCESS;
899         int first = 0;
900         int dostop = 0;
901         ber_socket_t s;
902         int i, defer = 1;
903         Backend *be;
904
905         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
906
907         if ( si == NULL )
908                 return NULL;
909
910         ldap_pvt_thread_mutex_lock( &si->si_mutex );
911
912         switch( abs( si->si_type )) {
913         case LDAP_SYNC_REFRESH_ONLY:
914         case LDAP_SYNC_REFRESH_AND_PERSIST:
915                 break;
916         default:
917                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
918                 return NULL;
919         }
920
921         if ( slapd_shutdown ) {
922                 if ( si->si_ld ) {
923                         ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
924                         connection_client_stop( s );
925                         ldap_unbind_ext( si->si_ld, NULL, NULL );
926                         si->si_ld = NULL;
927                 }
928                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
929                 return NULL;
930         }
931
932         op = (Operation *)opbuf;
933         connection_fake_init( &conn, op, ctx );
934
935         /* use global malloc for now */
936         op->o_tmpmemctx = NULL;
937         op->o_tmpmfuncs = &ch_mfuncs;
938
939         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
940         op->o_bd = be = si->si_be;
941         op->o_dn = op->o_bd->be_rootdn;
942         op->o_ndn = op->o_bd->be_rootndn;
943
944         /* Establish session, do search */
945         if ( !si->si_ld ) {
946                 first = 1;
947                 si->si_refreshDelete = 0;
948                 si->si_refreshPresent = 0;
949                 rc = do_syncrep1( op, si );
950         }
951
952         /* Process results */
953         if ( rc == LDAP_SUCCESS ) {
954                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
955
956                 rc = do_syncrep2( op, si );
957
958                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
959                         /* If we succeeded, enable the connection for further listening.
960                          * If we failed, tear down the connection and reschedule.
961                          */
962                         if ( rc == LDAP_SUCCESS ) {
963                                 if ( first ) {
964                                         rc = connection_client_setup( s, do_syncrepl, arg );
965                                 } else {
966                                         connection_client_enable( s );
967                                 } 
968                         } else if ( !first ) {
969                                 dostop = 1;
970                         }
971                 } else {
972                         if ( rc == -2 ) rc = 0;
973                 }
974         }
975
976         /* At this point, we have 4 cases:
977          * 1) for any hard failure, give up and remove this task
978          * 2) for ServerDown, reschedule this task to run
979          * 3) for Refresh and Success, reschedule to run
980          * 4) for Persist and Success, reschedule to defer
981          */
982         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
983
984         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
985                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
986         }
987
988         if ( dostop ) {
989                 connection_client_stop( s );
990         }
991
992         if ( rc == LDAP_SUCCESS ) {
993                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
994                         defer = 0;
995                 }
996                 rtask->interval.tv_sec = si->si_interval;
997                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
998                 if ( si->si_retrynum ) {
999                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
1000                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1001                         }
1002                         si->si_retrynum[i] = -2;
1003                 }
1004         } else {
1005                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1006                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
1007                                 break;
1008                 }
1009
1010                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
1011                         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1012                 } else if ( si->si_retrynum[i] >= -1 ) {
1013                         if ( si->si_retrynum[i] > 0 )
1014                                 si->si_retrynum[i]--;
1015                         rtask->interval.tv_sec = si->si_retryinterval[i];
1016                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1017                         slap_wake_listener();
1018                 }
1019         }
1020         
1021         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1022         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1023
1024         return NULL;
1025 }
1026
1027 static int
1028 syncrepl_message_to_entry(
1029         syncinfo_t      *si,
1030         Operation       *op,
1031         LDAPMessage     *msg,
1032         Modifications   **modlist,
1033         Entry                   **entry,
1034         int             syncstate
1035 )
1036 {
1037         Entry           *e = NULL;
1038         BerElement      *ber = NULL;
1039         Modifications   tmp;
1040         Modifications   *mod;
1041         Modifications   **modtail = modlist;
1042
1043         const char      *text;
1044         char txtbuf[SLAP_TEXT_BUFLEN];
1045         size_t textlen = sizeof txtbuf;
1046
1047         struct berval   bdn = {0, NULL}, dn, ndn;
1048         int             rc;
1049
1050         *modlist = NULL;
1051
1052         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1053                 Debug( LDAP_DEBUG_ANY,
1054                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1055                 return -1;
1056         }
1057
1058         op->o_tag = LDAP_REQ_ADD;
1059
1060         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1061
1062         if ( rc != LDAP_SUCCESS ) {
1063                 Debug( LDAP_DEBUG_ANY,
1064                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1065                 return rc;
1066         }
1067
1068         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1069         ber_dupbv( &op->o_req_dn, &dn );
1070         ber_dupbv( &op->o_req_ndn, &ndn );
1071         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1072         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1073
1074         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1075                 if ( entry )
1076                         *entry = NULL;
1077                 return LDAP_SUCCESS;
1078         }
1079
1080         if ( entry == NULL ) {
1081                 return -1;
1082         }
1083
1084         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1085         *entry = e;
1086         e->e_name = op->o_req_dn;
1087         e->e_nname = op->o_req_ndn;
1088
1089         while ( ber_remaining( ber ) ) {
1090                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1091                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1092                 {
1093                         break;
1094                 }
1095
1096                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1097
1098                 mod->sml_op = LDAP_MOD_REPLACE;
1099                 mod->sml_flags = 0;
1100                 mod->sml_next = NULL;
1101                 mod->sml_desc = NULL;
1102                 mod->sml_type = tmp.sml_type;
1103                 mod->sml_values = tmp.sml_values;
1104                 mod->sml_nvalues = NULL;
1105                 mod->sml_managing = 0;
1106
1107                 *modtail = mod;
1108                 modtail = &mod->sml_next;
1109         }
1110
1111         if ( *modlist == NULL ) {
1112                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1113                         0, 0, 0 );
1114                 rc = -1;
1115                 goto done;
1116         }
1117
1118         rc = slap_mods_check( *modlist, &text, txtbuf, textlen, NULL );
1119
1120         if ( rc != LDAP_SUCCESS ) {
1121                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1122                         text, 0, 0 );
1123                 goto done;
1124         }
1125
1126         /* Strip out dynamically generated attrs */
1127         for ( modtail = modlist; *modtail ; ) {
1128                 mod = *modtail;
1129                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1130                         *modtail = mod->sml_next;
1131                         slap_mod_free( &mod->sml_mod, 0 );
1132                         ch_free( mod );
1133                 } else {
1134                         modtail = &mod->sml_next;
1135                 }
1136         }
1137
1138         /* Strip out attrs in exattrs list */
1139         for ( modtail = modlist; *modtail ; ) {
1140                 mod = *modtail;
1141                 if ( ldap_charray_inlist( si->si_exattrs,
1142                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1143                         *modtail = mod->sml_next;
1144                         slap_mod_free( &mod->sml_mod, 0 );
1145                         ch_free( mod );
1146                 } else {
1147                         modtail = &mod->sml_next;
1148                 }
1149         }
1150         
1151         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1152         if( rc != LDAP_SUCCESS ) {
1153                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1154                         text, 0, 0 );
1155         }
1156
1157 done:
1158         ber_free ( ber, 0 );
1159         if ( rc != LDAP_SUCCESS ) {
1160                 if ( e ) {
1161                         entry_free( e );
1162                         *entry = e = NULL;
1163                 }
1164         }
1165
1166         return rc;
1167 }
1168
1169 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1170
1171 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1172  * entry if a previous refresh was interrupted before sending us a new
1173  * context state. We try to compare the new entry to the existing entry
1174  * and ignore the new entry if they are the same.
1175  *
1176  * Also, we may get an update where the entryDN has changed, due to
1177  * a ModDn on the provider. We detect this as well, so we can issue
1178  * the corresponding operation locally.
1179  *
1180  * In the case of a modify, we get a list of all the attributes
1181  * in the original entry. Rather than deleting the entry and re-adding it,
1182  * we issue a Modify request that deletes all the attributes and adds all
1183  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1184  * entry.
1185  *
1186  * We don't try to otherwise distinguish ModDN from Modify; in the case of
1187  * a ModDN we will issue both operations on the local database.
1188  */
1189 typedef struct dninfo {
1190         Entry *new_entry;
1191         struct berval dn;
1192         struct berval ndn;
1193         int renamed;    /* Was an existing entry renamed? */
1194         int wasChanged; /* are the attributes changed? */
1195         int attrs;              /* how many attribute types are in the ads list */
1196         AttributeDescription **ads;
1197 } dninfo;
1198
1199 static int
1200 syncrepl_entry(
1201         syncinfo_t* si,
1202         Operation *op,
1203         Entry* entry,
1204         Modifications** modlist,
1205         int syncstate,
1206         struct berval* syncUUID,
1207         struct sync_cookie* syncCookie_req,
1208         struct berval* syncCSN )
1209 {
1210         Backend *be = op->o_bd;
1211         slap_callback   cb = { NULL, NULL, NULL, NULL };
1212         struct berval   *syncuuid_bv = NULL;
1213         struct berval   syncUUID_strrep = BER_BVNULL;
1214         struct berval   uuid_bv = BER_BVNULL;
1215
1216         SlapReply       rs_search = {REP_RESULT};
1217         SlapReply       rs_delete = {REP_RESULT};
1218         SlapReply       rs_add = {REP_RESULT};
1219         SlapReply       rs_modify = {REP_RESULT};
1220         Filter f = {0};
1221 #ifdef LDAP_COMP_MATCH
1222         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1223 #else
1224         AttributeAssertion ava = { NULL, BER_BVNULL };
1225 #endif
1226         int rc = LDAP_SUCCESS;
1227         int ret = LDAP_SUCCESS;
1228
1229         struct berval pdn = BER_BVNULL;
1230         dninfo dni = {0};
1231         int     retry = 1;
1232
1233         switch( syncstate ) {
1234         case LDAP_SYNC_PRESENT:
1235                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1236                                         "syncrepl_entry",
1237                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1238                 break;
1239         case LDAP_SYNC_ADD:
1240                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1241                                         "syncrepl_entry",
1242                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1243                 break;
1244         case LDAP_SYNC_DELETE:
1245                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1246                                         "syncrepl_entry",
1247                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1248                 break;
1249         case LDAP_SYNC_MODIFY:
1250                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1251                                         "syncrepl_entry",
1252                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1253                 break;
1254         default:
1255                 Debug( LDAP_DEBUG_ANY, "%s: %s\n",
1256                                         "syncrepl_entry",
1257                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1258         }
1259
1260         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1261                 if ( !si->si_refreshPresent ) {
1262                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1263                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1264                                 syncuuid_cmp, avl_dup_error );
1265                 }
1266         }
1267
1268         if ( syncstate == LDAP_SYNC_PRESENT ) {
1269                 return 0;
1270         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1271                 if ( entry == NULL ) {
1272                         return 0;
1273                 }
1274         }
1275
1276         f.f_choice = LDAP_FILTER_EQUALITY;
1277         f.f_ava = &ava;
1278         ava.aa_desc = slap_schema.si_ad_entryUUID;
1279         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1280         ava.aa_value = *syncUUID;
1281         op->ors_filter = &f;
1282
1283         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID->bv_len;
1284         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1285                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1286         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1287         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1288                 syncUUID->bv_val, syncUUID->bv_len );
1289         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1290         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1291
1292         op->o_tag = LDAP_REQ_SEARCH;
1293         op->ors_scope = LDAP_SCOPE_SUBTREE;
1294         op->ors_deref = LDAP_DEREF_NEVER;
1295
1296         /* get the entry for this UUID */
1297         op->o_req_dn = si->si_base;
1298         op->o_req_ndn = si->si_base;
1299
1300         op->o_time = slap_get_time();
1301         op->ors_tlimit = SLAP_NO_LIMIT;
1302         op->ors_slimit = 1;
1303
1304         op->ors_attrs = slap_anlist_all_attributes;
1305         op->ors_attrsonly = 0;
1306
1307         /* set callback function */
1308         op->o_callback = &cb;
1309         cb.sc_response = dn_callback;
1310         cb.sc_private = &dni;
1311         dni.new_entry = entry;
1312
1313         if ( limits_check( op, &rs_search ) == 0 ) {
1314                 rc = be->be_search( op, &rs_search );
1315                 Debug( LDAP_DEBUG_SYNC,
1316                                 "syncrepl_entry: %s (%d)\n", 
1317                                 "be_search", rc, 0 );
1318         }
1319
1320         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1321                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1322         }
1323
1324         cb.sc_response = null_callback;
1325         cb.sc_private = si;
1326
1327         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1328                 Debug( LDAP_DEBUG_SYNC,
1329                                 "syncrepl_entry: %s\n",
1330                                 entry->e_name.bv_val, 0, 0 );
1331         } else {
1332                 Debug( LDAP_DEBUG_SYNC,
1333                                 "syncrepl_entry: %s\n",
1334                                 dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0, 0 );
1335         }
1336
1337         if ( syncstate != LDAP_SYNC_DELETE ) {
1338                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1339
1340                 if ( a == NULL ) {
1341                         /* add if missing */
1342                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1343                                 &syncUUID_strrep, syncUUID );
1344
1345                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1346                         /* replace only if necessary */
1347                         if ( a->a_nvals != a->a_vals ) {
1348                                 ber_memfree( a->a_nvals[0].bv_val );
1349                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1350                         }
1351                         ber_memfree( a->a_vals[0].bv_val );
1352                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1353                 }
1354         }
1355
1356         switch ( syncstate ) {
1357         case LDAP_SYNC_ADD:
1358         case LDAP_SYNC_MODIFY:
1359 retry_add:;
1360                 if ( BER_BVISNULL( &dni.dn )) {
1361
1362                         op->o_req_dn = entry->e_name;
1363                         op->o_req_ndn = entry->e_nname;
1364                         op->o_tag = LDAP_REQ_ADD;
1365                         op->ora_e = entry;
1366
1367                         rc = be->be_add( op, &rs_add );
1368                         Debug( LDAP_DEBUG_SYNC,
1369                                         "syncrepl_entry: %s (%d)\n", 
1370                                         "be_add", rc, 0 );
1371                         switch ( rs_add.sr_err ) {
1372                         case LDAP_SUCCESS:
1373                                 be_entry_release_w( op, entry );
1374                                 ret = 0;
1375                                 break;
1376
1377                         case LDAP_REFERRAL:
1378                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1379                          * only if the suffix entry is not present */
1380                         case LDAP_NO_SUCH_OBJECT:
1381                                 syncrepl_add_glue( op, entry );
1382                                 ret = 0;
1383                                 break;
1384
1385                         /* if an entry was added via syncrepl_add_glue(),
1386                          * it likely has no entryUUID, so the previous
1387                          * be_search() doesn't find it.  In this case,
1388                          * give syncrepl a chance to modify it. Also
1389                          * allow for entries that were recreated with the
1390                          * same DN but a different entryUUID.
1391                          */
1392                         case LDAP_ALREADY_EXISTS:
1393                                 if ( retry ) {
1394                                         Operation       op2 = *op;
1395                                         SlapReply       rs2 = { 0 };
1396                                         slap_callback   cb2 = { 0 };
1397
1398                                         op2.o_tag = LDAP_REQ_SEARCH;
1399                                         op2.o_req_dn = entry->e_name;
1400                                         op2.o_req_ndn = entry->e_nname;
1401                                         op2.ors_scope = LDAP_SCOPE_BASE;
1402                                         op2.ors_deref = LDAP_DEREF_NEVER;
1403                                         op2.ors_attrs = slap_anlist_all_attributes;
1404                                         op2.ors_attrsonly = 0;
1405                                         op2.ors_limit = NULL;
1406                                         op2.ors_slimit = 1;
1407                                         op2.ors_tlimit = SLAP_NO_LIMIT;
1408
1409                                         f.f_choice = LDAP_FILTER_PRESENT;
1410                                         f.f_desc = slap_schema.si_ad_objectClass;
1411                                         op2.ors_filter = &f;
1412                                         op2.ors_filterstr = generic_filterstr;
1413
1414                                         op2.o_callback = &cb2;
1415                                         cb2.sc_response = dn_callback;
1416                                         cb2.sc_private = &dni;
1417
1418                                         be->be_search( &op2, &rs2 );
1419
1420                                         retry = 0;
1421                                         goto retry_add;
1422                                 }
1423                                 /* FALLTHRU */
1424
1425                         default:
1426                                 Debug( LDAP_DEBUG_ANY,
1427                                         "syncrepl_entry : be_add failed (%d)\n",
1428                                         rs_add.sr_err, 0, 0 );
1429                                 ret = 1;
1430                                 break;
1431                         }
1432                         goto done;
1433                 }
1434                 /* FALLTHRU */
1435                 op->o_req_dn = dni.dn;
1436                 op->o_req_ndn = dni.ndn;
1437                 if ( dni.renamed ) {
1438                         struct berval noldp, newp, nnewp;
1439
1440                         op->o_tag = LDAP_REQ_MODRDN;
1441                         dnRdn( &entry->e_name, &op->orr_newrdn );
1442                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
1443
1444                         dnParent( &dni.ndn, &noldp );
1445                         dnParent( &entry->e_nname, &nnewp );
1446                         if ( !dn_match( &noldp, &newp )) {
1447                                 dnParent( &entry->e_name, &newp );
1448                                 op->orr_newSup = &newp;
1449                                 op->orr_nnewSup = &nnewp;
1450                         }
1451                         op->orr_deleteoldrdn = 0;
1452                         rc = be->be_modrdn( op, &rs_modify );
1453                         Debug( LDAP_DEBUG_SYNC,
1454                                         "syncrepl_entry: %s (%d)\n", 
1455                                         "be_modrdn", rc, 0 );
1456                         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
1457                                 op->o_req_dn = entry->e_name;
1458                                 op->o_req_ndn = entry->e_nname;
1459                         } else {
1460                                 ret = 1;
1461                                 goto done;
1462                         }
1463                 }
1464                 if ( dni.wasChanged ) {
1465                         Modifications *mod, *modhead = NULL;
1466                         Modifications *modtail = NULL;
1467                         int i;
1468
1469                         op->o_tag = LDAP_REQ_MODIFY;
1470
1471                         assert( *modlist != NULL );
1472
1473                         /* Delete all the old attrs */
1474                         for ( i = 0; i < dni.attrs; i++ ) {
1475                                 mod = ch_malloc( sizeof( Modifications ) );
1476                                 mod->sml_op = LDAP_MOD_DELETE;
1477                                 mod->sml_flags = 0;
1478                                 mod->sml_desc = dni.ads[i];
1479                                 mod->sml_type = mod->sml_desc->ad_cname;
1480                                 mod->sml_values = NULL;
1481                                 mod->sml_nvalues = NULL;
1482                                 mod->sml_managing = 0;
1483                                 if ( !modhead ) modhead = mod;
1484                                 if ( modtail ) {
1485                                         modtail->sml_next = mod;
1486                                 }
1487                                 modtail = mod;
1488                         }
1489
1490                         /* Append passed in list to ours */
1491                         if ( modtail ) {
1492                                 modtail->sml_next = *modlist;
1493                                 *modlist = modhead;
1494                         } else {
1495                                 mod = *modlist;
1496                         }
1497
1498                         /* Find end of this list */
1499                         for ( ; mod != NULL; mod = mod->sml_next ) {
1500                                 modtail = mod;
1501                         }
1502
1503                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1504                         mod->sml_op = LDAP_MOD_REPLACE;
1505                         mod->sml_flags = 0;
1506                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1507                         mod->sml_type = mod->sml_desc->ad_cname;
1508                         ber_dupbv( &uuid_bv, &syncUUID_strrep );
1509                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1510                         ber_dupbv( &uuid_bv, syncUUID );
1511                         ber_bvarray_add( &mod->sml_nvalues, &uuid_bv );
1512                         mod->sml_managing = 0;
1513                         modtail->sml_next = mod;
1514                                         
1515                         op->o_tag = LDAP_REQ_MODIFY;
1516                         op->orm_modlist = *modlist;
1517
1518                         rc = be->be_modify( op, &rs_modify );
1519                         Debug( LDAP_DEBUG_SYNC,
1520                                         "syncrepl_entry: %s (%d)\n", 
1521                                         "be_modify", rc, 0 );
1522                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1523                                 Debug( LDAP_DEBUG_ANY,
1524                                         "syncrepl_entry : be_modify failed (%d)\n",
1525                                         rs_modify.sr_err, 0, 0 );
1526                         }
1527                 }
1528                 ret = 1;
1529                 goto done;
1530         case LDAP_SYNC_DELETE :
1531                 if ( !BER_BVISNULL( &dni.dn )) {
1532                         op->o_req_dn = dni.dn;
1533                         op->o_req_ndn = dni.ndn;
1534                         op->o_tag = LDAP_REQ_DELETE;
1535                         rc = be->be_delete( op, &rs_delete );
1536                         Debug( LDAP_DEBUG_SYNC,
1537                                         "syncrepl_entry: %s (%d)\n", 
1538                                         "be_delete", rc, 0 );
1539
1540                         while ( rs_delete.sr_err == LDAP_SUCCESS
1541                                 && op->o_delete_glue_parent ) {
1542                                 op->o_delete_glue_parent = 0;
1543                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1544                                         slap_callback cb = { NULL };
1545                                         cb.sc_response = slap_null_cb;
1546                                         dnParent( &op->o_req_ndn, &pdn );
1547                                         op->o_req_dn = pdn;
1548                                         op->o_req_ndn = pdn;
1549                                         op->o_callback = &cb;
1550                                         op->o_bd->be_delete( op, &rs_delete );
1551                                 } else {
1552                                         break;
1553                                 }
1554                         }
1555                 }
1556                 ret = 0;
1557                 goto done;
1558
1559         default :
1560                 Debug( LDAP_DEBUG_ANY,
1561                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1562                 ret = 1;
1563                 goto done;
1564         }
1565
1566 done :
1567         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
1568                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1569                 BER_BVZERO( &syncUUID_strrep );
1570         }
1571         if ( dni.ads ) {
1572                 op->o_tmpfree( dni.ads, op->o_tmpmemctx );
1573         }
1574         if ( !BER_BVISNULL( &dni.ndn ) ) {
1575                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
1576         }
1577         if ( !BER_BVISNULL( &dni.dn ) ) {
1578                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
1579         }
1580         return ret;
1581 }
1582
1583 static struct berval gcbva[] = {
1584         BER_BVC("top"),
1585         BER_BVC("glue"),
1586         BER_BVNULL
1587 };
1588
1589 #define NP_DELETE_ONE   2
1590
1591 static void
1592 syncrepl_del_nonpresent(
1593         Operation *op,
1594         syncinfo_t *si,
1595         BerVarray uuids )
1596 {
1597         Backend* be = op->o_bd;
1598         slap_callback   cb = { NULL };
1599         SlapReply       rs_search = {REP_RESULT};
1600         SlapReply       rs_delete = {REP_RESULT};
1601         SlapReply       rs_modify = {REP_RESULT};
1602         struct nonpresent_entry *np_list, *np_prev;
1603         int rc;
1604         AttributeName   an[2];
1605
1606         struct berval pdn = BER_BVNULL;
1607
1608         op->o_req_dn = si->si_base;
1609         op->o_req_ndn = si->si_base;
1610
1611         cb.sc_response = nonpresent_callback;
1612         cb.sc_private = si;
1613
1614         op->o_callback = &cb;
1615         op->o_tag = LDAP_REQ_SEARCH;
1616         op->ors_scope = si->si_scope;
1617         op->ors_deref = LDAP_DEREF_NEVER;
1618         op->o_time = slap_get_time();
1619         op->ors_tlimit = SLAP_NO_LIMIT;
1620
1621
1622         if ( uuids ) {
1623                 Filter uf;
1624 #ifdef LDAP_COMP_MATCH
1625                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
1626 #else
1627                 AttributeAssertion eq = { NULL, BER_BVNULL };
1628 #endif
1629                 int i;
1630
1631                 op->ors_attrsonly = 1;
1632                 op->ors_attrs = slap_anlist_no_attrs;
1633                 op->ors_limit = NULL;
1634                 op->ors_filter = &uf;
1635
1636                 uf.f_ava = &eq;
1637                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
1638                 uf.f_next = NULL;
1639                 uf.f_choice = LDAP_FILTER_EQUALITY;
1640                 si->si_refreshDelete |= NP_DELETE_ONE;
1641
1642                 for (i=0; uuids[i].bv_val; i++) {
1643                         op->ors_slimit = 1;
1644                         uf.f_av_value = uuids[i];
1645                         rc = be->be_search( op, &rs_search );
1646                 }
1647                 si->si_refreshDelete ^= NP_DELETE_ONE;
1648         } else {
1649                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
1650                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1651                 an[0].an_desc = slap_schema.si_ad_entryUUID;
1652                 op->ors_attrs = an;
1653                 op->ors_slimit = SLAP_NO_LIMIT;
1654                 op->ors_attrsonly = 0;
1655                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
1656                 op->ors_filterstr = si->si_filterstr;
1657                 op->o_nocaching = 1;
1658
1659                 if ( limits_check( op, &rs_search ) == 0 ) {
1660                         rc = be->be_search( op, &rs_search );
1661                 }
1662                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
1663         }
1664
1665         op->o_nocaching = 0;
1666
1667         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
1668
1669                 slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
1670
1671                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
1672                 while ( np_list != NULL ) {
1673                         LDAP_LIST_REMOVE( np_list, npe_link );
1674                         np_prev = np_list;
1675                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
1676                         op->o_tag = LDAP_REQ_DELETE;
1677                         op->o_callback = &cb;
1678                         cb.sc_response = null_callback;
1679                         cb.sc_private = si;
1680                         op->o_req_dn = *np_prev->npe_name;
1681                         op->o_req_ndn = *np_prev->npe_nname;
1682                         rc = op->o_bd->be_delete( op, &rs_delete );
1683
1684                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
1685                                 Modifications mod1, mod2;
1686                                 mod1.sml_op = LDAP_MOD_REPLACE;
1687                                 mod1.sml_flags = 0;
1688                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
1689                                 mod1.sml_type = mod1.sml_desc->ad_cname;
1690                                 mod1.sml_values = &gcbva[0];
1691                                 mod1.sml_nvalues = NULL;
1692                                 mod1.sml_next = &mod2;
1693
1694                                 mod2.sml_op = LDAP_MOD_REPLACE;
1695                                 mod2.sml_flags = 0;
1696                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
1697                                 mod2.sml_type = mod2.sml_desc->ad_cname;
1698                                 mod2.sml_values = &gcbva[1];
1699                                 mod2.sml_nvalues = NULL;
1700                                 mod2.sml_next = NULL;
1701
1702                                 op->o_tag = LDAP_REQ_MODIFY;
1703                                 op->orm_modlist = &mod1;
1704
1705                                 rc = be->be_modify( op, &rs_modify );
1706                         }
1707
1708                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
1709                                         op->o_delete_glue_parent ) {
1710                                 op->o_delete_glue_parent = 0;
1711                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1712                                         slap_callback cb = { NULL };
1713                                         cb.sc_response = slap_null_cb;
1714                                         dnParent( &op->o_req_ndn, &pdn );
1715                                         op->o_req_dn = pdn;
1716                                         op->o_req_ndn = pdn;
1717                                         op->o_callback = &cb;
1718                                         /* give it a root privil ? */
1719                                         op->o_bd->be_delete( op, &rs_delete );
1720                                 } else {
1721                                         break;
1722                             }
1723                         }
1724
1725                         op->o_delete_glue_parent = 0;
1726
1727                         ber_bvfree( np_prev->npe_name );
1728                         ber_bvfree( np_prev->npe_nname );
1729                         ch_free( np_prev );
1730                 }
1731
1732                 slap_graduate_commit_csn( op );
1733         }
1734
1735         return;
1736 }
1737
1738 void
1739 syncrepl_add_glue(
1740         Operation* op,
1741         Entry *e )
1742 {
1743         Backend *be = op->o_bd;
1744         slap_callback cb = { NULL };
1745         Attribute       *a;
1746         int     rc;
1747         int suffrdns;
1748         int i;
1749         struct berval dn = {0, NULL};
1750         struct berval ndn = {0, NULL};
1751         Entry   *glue;
1752         SlapReply       rs_add = {REP_RESULT};
1753         char    *ptr, *comma;
1754
1755         op->o_tag = LDAP_REQ_ADD;
1756         op->o_callback = &cb;
1757         cb.sc_response = null_callback;
1758         cb.sc_private = NULL;
1759
1760         dn = e->e_name;
1761         ndn = e->e_nname;
1762
1763         /* count RDNs in suffix */
1764         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
1765                 for ( i = 0, ptr = be->be_nsuffix[0].bv_val; ptr; ptr = strchr( ptr, ',' ) ) {
1766                         ptr++;
1767                         i++;
1768                 }
1769                 suffrdns = i;
1770         } else {
1771                 /* suffix is "" */
1772                 suffrdns = 0;
1773         }
1774
1775         /* Start with BE suffix */
1776         for ( i = 0, ptr = NULL; i < suffrdns; i++ ) {
1777                 comma = strrchr( dn.bv_val, ',' );
1778                 if ( ptr ) *ptr = ',';
1779                 if ( comma ) *comma = '\0';
1780                 ptr = comma;
1781         }
1782         if ( ptr ) {
1783                 *ptr++ = ',';
1784                 dn.bv_len -= ptr - dn.bv_val;
1785                 dn.bv_val = ptr;
1786         }
1787         /* the normalizedDNs are always the same length, no counting
1788          * required.
1789          */
1790         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
1791                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
1792                 ndn.bv_len = be->be_nsuffix[0].bv_len;
1793         }
1794
1795         while ( ndn.bv_val > e->e_nname.bv_val ) {
1796                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
1797                 ber_dupbv( &glue->e_name, &dn );
1798                 ber_dupbv( &glue->e_nname, &ndn );
1799
1800                 a = ch_calloc( 1, sizeof( Attribute ));
1801                 a->a_desc = slap_schema.si_ad_objectClass;
1802
1803                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
1804                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
1805                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
1806                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
1807
1808                 a->a_nvals = a->a_vals;
1809
1810                 a->a_next = glue->e_attrs;
1811                 glue->e_attrs = a;
1812
1813                 a = ch_calloc( 1, sizeof( Attribute ));
1814                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
1815
1816                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
1817                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
1818                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
1819
1820                 a->a_nvals = a->a_vals;
1821
1822                 a->a_next = glue->e_attrs;
1823                 glue->e_attrs = a;
1824
1825                 op->o_req_dn = glue->e_name;
1826                 op->o_req_ndn = glue->e_nname;
1827                 op->ora_e = glue;
1828                 rc = be->be_add ( op, &rs_add );
1829                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
1830                         be_entry_release_w( op, glue );
1831                 } else {
1832                 /* incl. ALREADY EXIST */
1833                         entry_free( glue );
1834                 }
1835
1836                 /* Move to next child */
1837                 for (ptr = dn.bv_val-2; ptr > e->e_name.bv_val && *ptr != ','; ptr--) {
1838                         /* empty */
1839                 }
1840                 if ( ptr == e->e_name.bv_val ) break;
1841                 dn.bv_val = ++ptr;
1842                 dn.bv_len = e->e_name.bv_len - (ptr-e->e_name.bv_val);
1843                 for( ptr = ndn.bv_val-2;
1844                         ptr > e->e_nname.bv_val && *ptr != ',';
1845                         ptr--)
1846                 {
1847                         /* empty */
1848                 }
1849                 ndn.bv_val = ++ptr;
1850                 ndn.bv_len = e->e_nname.bv_len - (ptr-e->e_nname.bv_val);
1851         }
1852
1853         op->o_req_dn = e->e_name;
1854         op->o_req_ndn = e->e_nname;
1855         op->ora_e = e;
1856         rc = be->be_add ( op, &rs_add );
1857         if ( rs_add.sr_err == LDAP_SUCCESS ) {
1858                 be_entry_release_w( op, e );
1859         } else {
1860                 entry_free( e );
1861         }
1862
1863         return;
1864 }
1865
1866 static void
1867 syncrepl_updateCookie(
1868         syncinfo_t *si,
1869         Operation *op,
1870         struct berval *pdn,
1871         struct sync_cookie *syncCookie )
1872 {
1873         Backend *be = op->o_bd;
1874         Modifications mod = { { 0 } };
1875         struct berval vals[ 2 ];
1876
1877         int rc;
1878
1879         slap_callback cb = { NULL };
1880         SlapReply       rs_modify = {REP_RESULT};
1881
1882         slap_sync_cookie_free( &si->si_syncCookie, 0 );
1883         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
1884
1885         mod.sml_op = LDAP_MOD_REPLACE;
1886         mod.sml_desc = slap_schema.si_ad_contextCSN;
1887         mod.sml_type = mod.sml_desc->ad_cname;
1888         mod.sml_values = vals;
1889         vals[0] = si->si_syncCookie.ctxcsn;
1890         vals[1].bv_val = NULL;
1891         vals[1].bv_len = 0;
1892
1893         slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
1894
1895         op->o_tag = LDAP_REQ_MODIFY;
1896
1897         assert( si->si_rid < 1000 );
1898
1899         cb.sc_response = null_callback;
1900         cb.sc_private = si;
1901
1902         op->o_callback = &cb;
1903         op->o_req_dn = op->o_bd->be_suffix[0];
1904         op->o_req_ndn = op->o_bd->be_nsuffix[0];
1905
1906         /* update contextCSN */
1907         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
1908         op->orm_modlist = &mod;
1909         rc = be->be_modify( op, &rs_modify );
1910         op->o_msgid = 0;
1911
1912         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1913                 Debug( LDAP_DEBUG_ANY,
1914                         "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
1915         }
1916
1917         slap_graduate_commit_csn( op );
1918
1919         return;
1920 }
1921
1922 static int
1923 dn_callback(
1924         Operation*      op,
1925         SlapReply*      rs )
1926 {
1927         dninfo *dni = op->o_callback->sc_private;
1928
1929         if ( rs->sr_type == REP_SEARCH ) {
1930                 if ( !BER_BVISNULL( &dni->dn ) ) {
1931                         Debug( LDAP_DEBUG_ANY,
1932                                 "dn_callback : consistency error - "
1933                                 "entryUUID is not unique\n", 0, 0, 0 );
1934                 } else {
1935                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
1936                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
1937                         /* If there is a new entry, see if it differs from the old.
1938                          * We compare the non-normalized values so that cosmetic changes
1939                          * in the provider are always propagated.
1940                          */
1941                         if ( dni->new_entry ) {
1942                                 Attribute *old, *new;
1943                                 int i;
1944
1945                                 /* Did the DN change? Note that we don't explicitly try to
1946                                  * discover if the deleteOldRdn argument applies here. It
1947                                  * would save an unnecessary Modify if we detected it, but
1948                                  * that's a fair amount of trouble to compare the two attr
1949                                  * lists in detail.
1950                                  */
1951                                 if ( !dn_match( &rs->sr_entry->e_name,
1952                                                 &dni->new_entry->e_name ) )
1953                                 {
1954                                         dni->renamed = 1;
1955                                 }
1956
1957                                 for ( i = 0, old = rs->sr_entry->e_attrs;
1958                                                 old;
1959                                                 i++, old = old->a_next )
1960                                         ;
1961
1962                                 dni->attrs = i;
1963
1964                                 /* We assume that attributes are saved in the same order
1965                                  * in the remote and local databases. So if we walk through
1966                                  * the attributeDescriptions one by one they should match in
1967                                  * lock step. If not, we signal a change. Otherwise we test
1968                                  * all the values...
1969                                  */
1970                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
1971                                                 old && new;
1972                                                 old = old->a_next, new = new->a_next )
1973                                 {
1974                                         if ( old->a_desc != new->a_desc ) {
1975                                                 dni->wasChanged = 1;
1976                                                 break;
1977                                         }
1978                                         for ( i = 0; ; i++ ) {
1979                                                 int nold, nnew;
1980                                                 nold = BER_BVISNULL( &old->a_vals[i] );
1981                                                 nnew = BER_BVISNULL( &new->a_vals[i] );
1982                                                 /* If both are empty, stop looking */
1983                                                 if ( nold && nnew ) {
1984                                                         break;
1985                                                 }
1986                                                 /* If they are different, stop looking */
1987                                                 if ( nold != nnew ) {
1988                                                         dni->wasChanged = 1;
1989                                                         break;
1990                                                 }
1991                                                 if ( ber_bvcmp( &old->a_vals[i], &new->a_vals[i] )) {
1992                                                         dni->wasChanged = 1;
1993                                                         break;
1994                                                 }
1995                                         }
1996                                         if ( dni->wasChanged ) break;
1997                                 }
1998                                 if ( dni->wasChanged ) {
1999                                         dni->ads = op->o_tmpalloc( dni->attrs *
2000                                                 sizeof(AttributeDescription *), op->o_tmpmemctx );
2001                                         i = 0;
2002                                         for ( old = rs->sr_entry->e_attrs; old; old = old->a_next ) {
2003                                                 dni->ads[i] = old->a_desc;
2004                                                 i++;
2005                                         }
2006                                 }
2007                         }
2008                 }
2009         } else if ( rs->sr_type == REP_RESULT ) {
2010                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2011                         Debug( LDAP_DEBUG_ANY,
2012                                 "dn_callback : consistency error - "
2013                                 "entryUUID is not unique\n", 0, 0, 0 );
2014                 }
2015         }
2016
2017         return LDAP_SUCCESS;
2018 }
2019
2020 static int
2021 nonpresent_callback(
2022         Operation*      op,
2023         SlapReply*      rs )
2024 {
2025         syncinfo_t *si = op->o_callback->sc_private;
2026         Attribute *a;
2027         int count = 0;
2028         struct berval* present_uuid = NULL;
2029         struct nonpresent_entry *np_entry;
2030
2031         if ( rs->sr_type == REP_RESULT ) {
2032                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2033                 si->si_presentlist = NULL;
2034
2035         } else if ( rs->sr_type == REP_SEARCH ) {
2036                 if ( !(si->si_refreshDelete & NP_DELETE_ONE )) {
2037                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2038
2039                         if ( a == NULL ) return 0;
2040
2041                         present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2042                                 syncuuid_cmp );
2043                 }
2044
2045                 if ( present_uuid == NULL ) {
2046                         np_entry = (struct nonpresent_entry *)
2047                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2048                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2049                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2050                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2051
2052                 } else {
2053                         avl_delete( &si->si_presentlist,
2054                                         &a->a_nvals[0], syncuuid_cmp );
2055                         ch_free( present_uuid->bv_val );
2056                         ch_free( present_uuid );
2057                 }
2058         }
2059         return LDAP_SUCCESS;
2060 }
2061
2062 static int
2063 null_callback(
2064         Operation*      op,
2065         SlapReply*      rs )
2066 {
2067         if ( rs->sr_err != LDAP_SUCCESS &&
2068                 rs->sr_err != LDAP_REFERRAL &&
2069                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2070                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2071                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2072         {
2073                 Debug( LDAP_DEBUG_ANY,
2074                         "null_callback : error code 0x%x\n",
2075                         rs->sr_err, 0, 0 );
2076         }
2077         return LDAP_SUCCESS;
2078 }
2079
2080 static struct berval *
2081 slap_uuidstr_from_normalized(
2082         struct berval* uuidstr,
2083         struct berval* normalized,
2084         void *ctx )
2085 {
2086         struct berval *new;
2087         unsigned char nibble;
2088         int i, d = 0;
2089
2090         if ( normalized == NULL ) return NULL;
2091         if ( normalized->bv_len != 16 ) return NULL;
2092
2093         if ( uuidstr ) {
2094                 new = uuidstr;
2095         } else {
2096                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2097                 if ( new == NULL ) {
2098                         return NULL;
2099                 }
2100         }
2101
2102         new->bv_len = 36;
2103
2104         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2105                 if ( new != uuidstr ) {
2106                         slap_sl_free( new, ctx );
2107                 }
2108                 return NULL;
2109         }
2110
2111         for ( i = 0; i < 16; i++ ) {
2112                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2113                         new->bv_val[(i<<1)+d] = '-';
2114                         d += 1;
2115                 }
2116
2117                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2118                 if ( nibble < 10 ) {
2119                         new->bv_val[(i<<1)+d] = nibble + '0';
2120                 } else {
2121                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2122                 }
2123
2124                 nibble = (normalized->bv_val[i]) & 0xF;
2125                 if ( nibble < 10 ) {
2126                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2127                 } else {
2128                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2129                 }
2130         }
2131
2132         new->bv_val[new->bv_len] = '\0';
2133         return new;
2134 }
2135
2136 static int
2137 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2138 {
2139         const struct berval *uuid1 = v_uuid1;
2140         const struct berval *uuid2 = v_uuid2;
2141         int rc = uuid1->bv_len - uuid2->bv_len;
2142         if ( rc ) return rc;
2143         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2144 }
2145
2146 static void
2147 avl_ber_bvfree( void *v_bv )
2148 {
2149         struct berval   *bv = (struct berval *)v_bv;
2150         
2151         if( v_bv == NULL ) return;
2152         if ( !BER_BVISNULL( bv ) ) {
2153                 ch_free( bv->bv_val );
2154         }
2155         ch_free( (char *) bv );
2156 }
2157
2158 void
2159 syncinfo_free( syncinfo_t *sie )
2160 {
2161         ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
2162         if ( !BER_BVISNULL( &sie->si_provideruri ) ) {
2163                 ch_free( sie->si_provideruri.bv_val );
2164         }
2165
2166         bindconf_free( &sie->si_bindconf );
2167
2168         if ( sie->si_filterstr.bv_val ) {
2169                 ch_free( sie->si_filterstr.bv_val );
2170         }
2171         if ( sie->si_base.bv_val ) {
2172                 ch_free( sie->si_base.bv_val );
2173         }
2174         if ( sie->si_attrs ) {
2175                 int i = 0;
2176                 while ( sie->si_attrs[i] != NULL ) {
2177                         ch_free( sie->si_attrs[i] );
2178                         i++;
2179                 }
2180                 ch_free( sie->si_attrs );
2181         }
2182         if ( sie->si_exattrs ) {
2183                 int i = 0;
2184                 while ( sie->si_exattrs[i] != NULL ) {
2185                         ch_free( sie->si_exattrs[i] );
2186                         i++;
2187                 }
2188                 ch_free( sie->si_exattrs );
2189         }
2190         if ( sie->si_anlist ) {
2191                 int i = 0;
2192                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2193                         ch_free( sie->si_anlist[i].an_name.bv_val );
2194                         i++;
2195                 }
2196                 ch_free( sie->si_anlist );
2197         }
2198         if ( sie->si_exanlist ) {
2199                 int i = 0;
2200                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2201                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2202                         i++;
2203                 }
2204                 ch_free( sie->si_exanlist );
2205         }
2206         if ( sie->si_retryinterval ) {
2207                 ch_free( sie->si_retryinterval );
2208         }
2209         if ( sie->si_retrynum ) {
2210                 ch_free( sie->si_retrynum );
2211         }
2212         if ( sie->si_retrynum_init ) {
2213                 ch_free( sie->si_retrynum_init );
2214         }
2215         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2216         if ( sie->si_presentlist ) {
2217             avl_free( sie->si_presentlist, avl_ber_bvfree );
2218         }
2219         if ( sie->si_ld ) {
2220                 ldap_ld_free( sie->si_ld, 1, NULL, NULL );
2221         }
2222         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2223                 struct nonpresent_entry* npe;
2224                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2225                 LDAP_LIST_REMOVE( npe, npe_link );
2226                 if ( npe->npe_name ) {
2227                         if ( npe->npe_name->bv_val ) {
2228                                 ch_free( npe->npe_name->bv_val );
2229                         }
2230                         ch_free( npe->npe_name );
2231                 }
2232                 if ( npe->npe_nname ) {
2233                         if ( npe->npe_nname->bv_val ) {
2234                                 ch_free( npe->npe_nname->bv_val );
2235                         }
2236                         ch_free( npe->npe_nname );
2237                 }
2238                 ch_free( npe );
2239         }
2240         ch_free( sie );
2241 }
2242
2243
2244
2245 /* NOTE: used & documented in slapd.conf(5) */
2246 #define IDSTR                   "rid"
2247 #define PROVIDERSTR             "provider"
2248 #define SCHEMASTR               "schemachecking"
2249 #define FILTERSTR               "filter"
2250 #define SEARCHBASESTR           "searchbase"
2251 #define SCOPESTR                "scope"
2252 #define ATTRSONLYSTR            "attrsonly"
2253 #define ATTRSSTR                "attrs"
2254 #define TYPESTR                 "type"
2255 #define INTERVALSTR             "interval"
2256 #define RETRYSTR                "retry"
2257 #define SLIMITSTR               "sizelimit"
2258 #define TLIMITSTR               "timelimit"
2259
2260 /* FIXME: undocumented */
2261 #define OLDAUTHCSTR             "bindprincipal"
2262 #define EXATTRSSTR              "exattrs"
2263 #define MANAGEDSAITSTR          "manageDSAit"
2264
2265 /* FIXME: unused */
2266 #define LASTMODSTR              "lastmod"
2267 #define LMGENSTR                "gen"
2268 #define LMNOSTR                 "no"
2269 #define LMREQSTR                "req"
2270 #define SRVTABSTR               "srvtab"
2271 #define SUFFIXSTR               "suffix"
2272
2273 /* mandatory */
2274 #define GOT_ID                  0x0001
2275 #define GOT_PROVIDER            0x0002
2276
2277 /* check */
2278 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER)
2279
2280 static struct {
2281         struct berval key;
2282         int val;
2283 } scopes[] = {
2284         { BER_BVC("base"), LDAP_SCOPE_BASE },
2285         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
2286         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
2287 #ifdef LDAP_SCOPE_SUBORDINATE
2288         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
2289         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
2290 #endif
2291         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
2292         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
2293         { BER_BVNULL, 0 }
2294 };
2295
2296 static int
2297 parse_syncrepl_line(
2298         char            **cargv,
2299         int             cargc,
2300         syncinfo_t      *si
2301 )
2302 {
2303         int     gots = 0;
2304         int     i;
2305         char    *val;
2306
2307         for ( i = 1; i < cargc; i++ ) {
2308                 if ( !strncasecmp( cargv[ i ], IDSTR "=",
2309                                         STRLENOF( IDSTR "=" ) ) )
2310                 {
2311                         int tmp;
2312                         /* '\0' string terminator accounts for '=' */
2313                         val = cargv[ i ] + STRLENOF( IDSTR "=" );
2314                         tmp= atoi( val );
2315                         if ( tmp >= 1000 || tmp < 0 ) {
2316                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2317                                          "syncrepl id %d is out of range [0..999]\n", tmp );
2318                                 return -1;
2319                         }
2320                         si->si_rid = tmp;
2321                         gots |= GOT_ID;
2322                 } else if ( !strncasecmp( cargv[ i ], PROVIDERSTR "=",
2323                                         STRLENOF( PROVIDERSTR "=" ) ) )
2324                 {
2325                         val = cargv[ i ] + STRLENOF( PROVIDERSTR "=" );
2326                         ber_str2bv( val, 0, 1, &si->si_provideruri );
2327                         gots |= GOT_PROVIDER;
2328                 } else if ( !strncasecmp( cargv[ i ], SCHEMASTR "=",
2329                                         STRLENOF( SCHEMASTR "=" ) ) )
2330                 {
2331                         val = cargv[ i ] + STRLENOF( SCHEMASTR "=" );
2332                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) )) {
2333                                 si->si_schemachecking = 1;
2334                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
2335                                 si->si_schemachecking = 0;
2336                         } else {
2337                                 si->si_schemachecking = 1;
2338                         }
2339                 } else if ( !strncasecmp( cargv[ i ], FILTERSTR "=",
2340                                         STRLENOF( FILTERSTR "=" ) ) )
2341                 {
2342                         val = cargv[ i ] + STRLENOF( FILTERSTR "=" );
2343                         ber_str2bv( val, 0, 1, &si->si_filterstr );
2344                 } else if ( !strncasecmp( cargv[ i ], SEARCHBASESTR "=",
2345                                         STRLENOF( SEARCHBASESTR "=" ) ) )
2346                 {
2347                         struct berval   bv;
2348                         int             rc;
2349
2350                         val = cargv[ i ] + STRLENOF( SEARCHBASESTR "=" );
2351                         if ( si->si_base.bv_val ) {
2352                                 ch_free( si->si_base.bv_val );
2353                         }
2354                         ber_str2bv( val, 0, 0, &bv );
2355                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
2356                         if ( rc != LDAP_SUCCESS ) {
2357                                 fprintf( stderr, "Invalid base DN \"%s\": %d (%s)\n",
2358                                         val, rc, ldap_err2string( rc ) );
2359                                 return -1;
2360                         }
2361                 } else if ( !strncasecmp( cargv[ i ], SCOPESTR "=",
2362                                         STRLENOF( SCOPESTR "=" ) ) )
2363                 {
2364                         int j;
2365                         val = cargv[ i ] + STRLENOF( SCOPESTR "=" );
2366                         for ( j=0; !BER_BVISNULL(&scopes[j].key); j++ ) {
2367                                 if (!strcasecmp( val, scopes[j].key.bv_val )) {
2368                                         si->si_scope = scopes[j].val;
2369                                         break;
2370                                 }
2371                         }
2372                         if ( BER_BVISNULL(&scopes[j].key) ) {
2373                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2374                                         "unknown scope \"%s\"\n", val);
2375                                 return -1;
2376                         }
2377                 } else if ( !strncasecmp( cargv[ i ], ATTRSONLYSTR "=",
2378                                         STRLENOF( ATTRSONLYSTR "=" ) ) )
2379                 {
2380                         si->si_attrsonly = 1;
2381                 } else if ( !strncasecmp( cargv[ i ], ATTRSSTR "=",
2382                                         STRLENOF( ATTRSSTR "=" ) ) )
2383                 {
2384                         val = cargv[ i ] + STRLENOF( ATTRSSTR "=" );
2385                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
2386                                 char *attr_fname;
2387                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2388                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
2389                                 if ( si->si_anlist == NULL ) {
2390                                         ch_free( attr_fname );
2391                                         return -1;
2392                                 }
2393                                 si->si_anfile = attr_fname;
2394                         } else {
2395                                 char *str, *s, *next;
2396                                 char delimstr[] = " ,\t";
2397                                 str = ch_strdup( val );
2398                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
2399                                                 s != NULL;
2400                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
2401                                 {
2402                                         if ( strlen(s) == 1 && *s == '*' ) {
2403                                                 si->si_allattrs = 1;
2404                                                 *(val + ( s - str )) = delimstr[0];
2405                                         }
2406                                         if ( strlen(s) == 1 && *s == '+' ) {
2407                                                 si->si_allopattrs = 1;
2408                                                 *(val + ( s - str )) = delimstr[0];
2409                                         }
2410                                 }
2411                                 ch_free( str );
2412                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
2413                                 if ( si->si_anlist == NULL ) {
2414                                         return -1;
2415                                 }
2416                         }
2417                 } else if ( !strncasecmp( cargv[ i ], EXATTRSSTR "=",
2418                                         STRLENOF( EXATTRSSTR "=" ) ) )
2419                 {
2420                         val = cargv[ i ] + STRLENOF( EXATTRSSTR "=" );
2421                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") )) {
2422                                 char *attr_fname;
2423                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2424                                 si->si_exanlist = file2anlist(
2425                                                                         si->si_exanlist, attr_fname, " ,\t" );
2426                                 if ( si->si_exanlist == NULL ) {
2427                                         ch_free( attr_fname );
2428                                         return -1;
2429                                 }
2430                                 ch_free( attr_fname );
2431                         } else {
2432                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
2433                                 if ( si->si_exanlist == NULL ) {
2434                                         return -1;
2435                                 }
2436                         }
2437                 } else if ( !strncasecmp( cargv[ i ], TYPESTR "=",
2438                                         STRLENOF( TYPESTR "=" ) ) )
2439                 {
2440                         val = cargv[ i ] + STRLENOF( TYPESTR "=" );
2441                         if ( !strncasecmp( val, "refreshOnly",
2442                                                 STRLENOF("refreshOnly") ))
2443                         {
2444                                 si->si_type = LDAP_SYNC_REFRESH_ONLY;
2445                         } else if ( !strncasecmp( val, "refreshAndPersist",
2446                                                 STRLENOF("refreshAndPersist") ))
2447                         {
2448                                 si->si_type = LDAP_SYNC_REFRESH_AND_PERSIST;
2449                                 si->si_interval = 60;
2450                         } else {
2451                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2452                                         "unknown sync type \"%s\"\n", val);
2453                                 return -1;
2454                         }
2455                 } else if ( !strncasecmp( cargv[ i ], INTERVALSTR "=",
2456                                         STRLENOF( INTERVALSTR "=" ) ) )
2457                 {
2458                         val = cargv[ i ] + STRLENOF( INTERVALSTR "=" );
2459                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
2460                                 si->si_interval = 0;
2461                         } else {
2462                                 char *hstr;
2463                                 char *mstr;
2464                                 char *dstr;
2465                                 char *sstr;
2466                                 int dd, hh, mm, ss;
2467                                 dstr = val;
2468                                 hstr = strchr( dstr, ':' );
2469                                 if ( hstr == NULL ) {
2470                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2471                                                 "invalid interval \"%s\"\n", val );
2472                                         return -1;
2473                                 }
2474                                 *hstr++ = '\0';
2475                                 mstr = strchr( hstr, ':' );
2476                                 if ( mstr == NULL ) {
2477                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2478                                                 "invalid interval \"%s\"\n", val );
2479                                         return -1;
2480                                 }
2481                                 *mstr++ = '\0';
2482                                 sstr = strchr( mstr, ':' );
2483                                 if ( sstr == NULL ) {
2484                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2485                                                 "invalid interval \"%s\"\n", val );
2486                                         return -1;
2487                                 }
2488                                 *sstr++ = '\0';
2489
2490                                 dd = atoi( dstr );
2491                                 hh = atoi( hstr );
2492                                 mm = atoi( mstr );
2493                                 ss = atoi( sstr );
2494                                 if (( hh > 24 ) || ( hh < 0 ) ||
2495                                         ( mm > 60 ) || ( mm < 0 ) ||
2496                                         ( ss > 60 ) || ( ss < 0 ) || ( dd < 0 )) {
2497                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2498                                                 "invalid interval \"%s\"\n", val );
2499                                         return -1;
2500                                 }
2501                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
2502                         }
2503                         if ( si->si_interval < 0 ) {
2504                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2505                                         "invalid interval \"%ld\"\n",
2506                                         (long) si->si_interval);
2507                                 return -1;
2508                         }
2509                 } else if ( !strncasecmp( cargv[ i ], RETRYSTR "=",
2510                                         STRLENOF( RETRYSTR "=" ) ) )
2511                 {
2512                         char **retry_list;
2513                         int j, k, n;
2514
2515                         val = cargv[ i ] + STRLENOF( RETRYSTR "=" );
2516                         retry_list = (char **) ch_calloc( 1, sizeof( char * ));
2517                         retry_list[0] = NULL;
2518
2519                         slap_str2clist( &retry_list, val, " ,\t" );
2520
2521                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
2522                         n = k / 2;
2523                         if ( k % 2 ) {
2524                                 fprintf( stderr,
2525                                                 "Error: incomplete syncrepl retry list\n" );
2526                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
2527                                         ch_free( retry_list[k] );
2528                                 }
2529                                 ch_free( retry_list );
2530                                 exit( EXIT_FAILURE );
2531                         }
2532                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ));
2533                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ));
2534                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ));
2535                         for ( j = 0; j < n; j++ ) {
2536                                 si->si_retryinterval[j] = atoi( retry_list[j*2] );
2537                                 if ( *retry_list[j*2+1] == '+' ) {
2538                                         si->si_retrynum_init[j] = -1;
2539                                         si->si_retrynum[j] = -1;
2540                                         j++;
2541                                         break;
2542                                 } else {
2543                                         si->si_retrynum_init[j] = atoi( retry_list[j*2+1] );
2544                                         si->si_retrynum[j] = atoi( retry_list[j*2+1] );
2545                                 }
2546                         }
2547                         si->si_retrynum_init[j] = -2;
2548                         si->si_retrynum[j] = -2;
2549                         si->si_retryinterval[j] = 0;
2550                         
2551                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
2552                                 ch_free( retry_list[k] );
2553                         }
2554                         ch_free( retry_list );
2555                 } else if ( !strncasecmp( cargv[ i ], MANAGEDSAITSTR "=",
2556                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
2557                 {
2558                         val = cargv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
2559                         si->si_manageDSAit = atoi( val );
2560                 } else if ( !strncasecmp( cargv[ i ], SLIMITSTR "=",
2561                                         STRLENOF( SLIMITSTR "=") ) )
2562                 {
2563                         val = cargv[ i ] + STRLENOF( SLIMITSTR "=" );
2564                         si->si_slimit = atoi( val );
2565                 } else if ( !strncasecmp( cargv[ i ], TLIMITSTR "=",
2566                                         STRLENOF( TLIMITSTR "=" ) ) )
2567                 {
2568                         val = cargv[ i ] + STRLENOF( TLIMITSTR "=" );
2569                         si->si_tlimit = atoi( val );
2570                 } else if ( bindconf_parse( cargv[i], &si->si_bindconf )) {
2571                         fprintf( stderr, "Error: parse_syncrepl_line: "
2572                                 "unknown keyword \"%s\"\n", cargv[ i ] );
2573                         return -1;
2574                 }
2575         }
2576
2577         if ( gots != GOT_ALL ) {
2578                 fprintf( stderr,
2579                         "Error: Malformed \"syncrepl\" line in slapd config file" );
2580                 return -1;
2581         }
2582
2583         return 0;
2584 }
2585
2586 static int
2587 add_syncrepl(
2588         Backend *be,
2589         char    **cargv,
2590         int     cargc
2591 )
2592 {
2593         syncinfo_t *si;
2594         int     rc = 0;
2595
2596         if ( !( be->be_search && be->be_add && be->be_modify && be->be_delete )) {
2597                 Debug( LDAP_DEBUG_ANY, "database %s does not support operations "
2598                         "required for syncrepl\n", be->be_type, 0, 0 );
2599                 return 1;
2600         }
2601         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
2602
2603         if ( si == NULL ) {
2604                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
2605                 return 1;
2606         }
2607
2608         si->si_bindconf.sb_tls = SB_TLS_OFF;
2609         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
2610         si->si_schemachecking = 0;
2611         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
2612                 &si->si_filterstr );
2613         si->si_base.bv_val = NULL;
2614         si->si_scope = LDAP_SCOPE_SUBTREE;
2615         si->si_attrsonly = 0;
2616         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
2617         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
2618         si->si_attrs = NULL;
2619         si->si_allattrs = 0;
2620         si->si_allopattrs = 0;
2621         si->si_exattrs = NULL;
2622         si->si_type = LDAP_SYNC_REFRESH_ONLY;
2623         si->si_interval = 86400;
2624         si->si_retryinterval = NULL;
2625         si->si_retrynum_init = NULL;
2626         si->si_retrynum = NULL;
2627         si->si_manageDSAit = 0;
2628         si->si_tlimit = 0;
2629         si->si_slimit = 0;
2630
2631         si->si_presentlist = NULL;
2632         LDAP_LIST_INIT( &si->si_nonpresentlist );
2633         ldap_pvt_thread_mutex_init( &si->si_mutex );
2634
2635         rc = parse_syncrepl_line( cargv, cargc, si );
2636
2637         if ( rc == 0 ) {
2638                 si->si_be = be;
2639                 init_syncrepl( si );
2640                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq, si->si_interval,
2641                         do_syncrepl, si, "do_syncrepl", be->be_suffix[0].bv_val );
2642                 if ( !si->si_re )
2643                         rc = -1;
2644         }
2645         if ( rc < 0 ) {
2646                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
2647                 syncinfo_free( si );    
2648                 return 1;
2649         } else {
2650                 Debug( LDAP_DEBUG_CONFIG,
2651                         "Config: ** successfully added syncrepl \"%s\"\n",
2652                         BER_BVISNULL( &si->si_provideruri ) ?
2653                         "(null)" : si->si_provideruri.bv_val, 0, 0 );
2654                 if ( !si->si_schemachecking ) {
2655                         SLAP_DBFLAGS(be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2656                 }
2657                 be->be_syncinfo = si;
2658                 return 0;
2659         }
2660 }
2661
2662 static void
2663 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
2664 {
2665         struct berval bc;
2666         char buf[BUFSIZ*2], *ptr;
2667         int i;
2668
2669         bindconf_unparse( &si->si_bindconf, &bc );
2670         ptr = buf;
2671         ptr += sprintf( ptr, IDSTR "=%03ld " PROVIDERSTR "=%s",
2672                 si->si_rid, si->si_provideruri.bv_val );
2673         if ( !BER_BVISNULL( &bc )) {
2674                 ptr = lutil_strcopy( ptr, bc.bv_val );
2675                 free( bc.bv_val );
2676         }
2677         if ( !BER_BVISEMPTY( &si->si_filterstr )) {
2678                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
2679                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
2680                 *ptr++ = '"';
2681         }
2682         if ( !BER_BVISNULL( &si->si_base )) {
2683                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
2684                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
2685                 *ptr++ = '"';
2686         }
2687         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
2688                 if ( si->si_scope == scopes[i].val ) {
2689                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
2690                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
2691                         break;
2692                 }
2693         }
2694         if ( si->si_attrsonly ) {
2695                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR "=yes" );
2696         }
2697         if ( si->si_anfile ) {
2698                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:" );
2699                 ptr = lutil_strcopy( ptr, si->si_anfile );
2700         } else if ( si->si_allattrs || si->si_allopattrs ||
2701                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) )) {
2702                 char *old;
2703                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
2704                 old = ptr;
2705                 ptr = anlist_unparse( si->si_anlist, ptr );
2706                 if ( si->si_allattrs ) {
2707                         if ( old != ptr ) *ptr++ = ',';
2708                         *ptr++ = '*';
2709                 }
2710                 if ( si->si_allopattrs ) {
2711                         if ( old != ptr ) *ptr++ = ',';
2712                         *ptr++ = '+';
2713                 }
2714                 *ptr++ = '"';
2715         }
2716         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
2717                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
2718                 ptr = anlist_unparse( si->si_exanlist, ptr );
2719         }
2720         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
2721         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
2722         
2723         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
2724         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
2725                 "refreshAndPersist" : "refreshOnly" );
2726
2727         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
2728                 int dd, hh, mm, ss;
2729
2730                 dd = si->si_interval;
2731                 ss = dd % 60;
2732                 dd /= 60;
2733                 mm = dd % 60;
2734                 dd /= 60;
2735                 hh = dd % 24;
2736                 dd /= 24;
2737                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
2738                 ptr += sprintf( ptr, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
2739         } else if ( si->si_retryinterval ) {
2740                 int space=0;
2741                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
2742                 for (i=0; si->si_retryinterval[i]; i++) {
2743                         if ( space ) *ptr++ = ' ';
2744                         space = 1;
2745                         ptr += sprintf( ptr, "%ld ", (long) si->si_retryinterval[i] );
2746                         if ( si->si_retrynum_init[i] == -1 )
2747                                 *ptr++ = '+';
2748                         else
2749                                 ptr += sprintf( ptr, "%d", si->si_retrynum_init[i] );
2750                 }
2751                 *ptr++ = '"';
2752         }
2753
2754         if ( si->si_slimit ) {
2755                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
2756                 ptr += sprintf( ptr, "%d", si->si_slimit );
2757         }
2758
2759         if ( si->si_tlimit ) {
2760                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
2761                 ptr += sprintf( ptr, "%d", si->si_tlimit );
2762         }
2763         bc.bv_len = ptr - buf;
2764         bc.bv_val = buf;
2765         ber_dupbv( bv, &bc );
2766 }
2767
2768 int
2769 syncrepl_config(ConfigArgs *c) {
2770         if (c->op == SLAP_CONFIG_EMIT) {
2771                 if ( c->be->be_syncinfo ) {
2772                         struct berval bv;
2773                         syncrepl_unparse( c->be->be_syncinfo, &bv ); 
2774                         ber_bvarray_add( &c->rvalue_vals, &bv );
2775                         return 0;
2776                 }
2777                 return 1;
2778         } else if ( c->op == LDAP_MOD_DELETE ) {
2779                 struct re_s *re;
2780
2781                 if ( c->be->be_syncinfo ) {
2782                         re = c->be->be_syncinfo->si_re;
2783                         if ( re ) {
2784                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ))
2785                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
2786                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
2787                         }
2788                         syncinfo_free( c->be->be_syncinfo );
2789                         c->be->be_syncinfo = NULL;
2790                 }
2791                 SLAP_DBFLAGS(c->be) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
2792                 return 0;
2793         }
2794         if(SLAP_SHADOW(c->be)) {
2795                 Debug(LDAP_DEBUG_ANY, "%s: "
2796                         "syncrepl: database already shadowed.\n",
2797                         c->log, 0, 0);
2798                 return(1);
2799         } else if(add_syncrepl(c->be, c->argv, c->argc)) {
2800                 return(1);
2801         }
2802         SLAP_DBFLAGS(c->be) |= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SYNC_SHADOW);
2803         return(0);
2804 }