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