]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
Fix strchrlen running past end of berval
[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 );
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 ( !BER_BVISNULL( &syncCookie.ctxcsn ) &&
812                                         match < 0 && err == LDAP_SUCCESS )
813                                 {
814                                         rc = syncrepl_updateCookie( si, op, psub, &syncCookie );
815                                 }
816                                 if ( rctrls ) {
817                                         ldap_controls_free( rctrls );
818                                 }
819                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
820                                         /* FIXME : different error behaviors according to
821                                          *      1) err code : LDAP_BUSY ...
822                                          *      2) on err policy : stop service, stop sync, retry
823                                          */
824                                         if ( refreshDeletes == 0 && match < 0 &&
825                                                 err == LDAP_SUCCESS )
826                                         {
827                                                 syncrepl_del_nonpresent( op, si, NULL );
828                                         } else {
829                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
830                                                 si->si_presentlist = NULL;
831                                         }
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                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
921                                                 } else {
922                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
923                                                                 struct berval *syncuuid_bv;
924                                                                 syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
925                                                                 slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
926                                                                 avl_insert( &si->si_presentlist,
927                                                                         (caddr_t) syncuuid_bv,
928                                                                         syncuuid_cmp, avl_dup_error );
929                                                         }
930                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
931                                                 }
932                                                 break;
933                                         default:
934                                                 Debug( LDAP_DEBUG_ANY,
935                                                         "do_syncrep2 : unknown syncinfo tag (%ld)\n",
936                                                 (long) si_tag, 0, 0 );
937                                                 ldap_memfree( retoid );
938                                                 ber_bvfree( retdata );
939                                                 continue;
940                                         }
941
942                                         if ( BER_BVISNULL( &syncCookie_req.ctxcsn )) {
943                                                 match = -1;
944                                         } else if ( BER_BVISNULL( &syncCookie.ctxcsn )) {
945                                                 match = 1;
946                                         } else {
947                                                 value_match( &match, slap_schema.si_ad_entryCSN,
948                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
949                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
950                                                         &syncCookie_req.ctxcsn,
951                                                         &syncCookie.ctxcsn, &text );
952                                         }
953
954                                         if ( !BER_BVISNULL( &syncCookie.ctxcsn ) &&
955                                                 match < 0 )
956                                         {
957                                                 rc = syncrepl_updateCookie( si, op, psub, &syncCookie);
958                                         }
959
960                                         if ( si->si_refreshPresent == 1 ) {
961                                                 if ( match < 0 ) {
962                                                         syncrepl_del_nonpresent( op, si, NULL );
963                                                 }
964                                         } 
965
966                                         ldap_memfree( retoid );
967                                         ber_bvfree( retdata );
968                                         break;
969
970                                 } else {
971                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
972                                                 "unknown intermediate response (%d)\n",
973                                                 rc, 0, 0 );
974                                         ldap_memfree( retoid );
975                                         ber_bvfree( retdata );
976                                         break;
977                                 }
978                                 break;
979
980                         default:
981                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
982                                         "unknown message\n", 0, 0, 0 );
983                                 break;
984
985                         }
986                         if ( !BER_BVISNULL( &syncCookie.octet_str )) {
987                                 slap_sync_cookie_free( &syncCookie_req, 0 );
988                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
989                                 slap_sync_cookie_free( &syncCookie, 0 );
990                         }
991                 }
992                 ldap_msgfree( res );
993                 res = NULL;
994         }
995
996         if ( rc == -1 ) {
997                 const char *errstr;
998
999                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
1000                 errstr = ldap_err2string( rc );
1001                 
1002                 Debug( LDAP_DEBUG_ANY,
1003                         "do_syncrep2 : %s\n", errstr, 0, 0 );
1004         }
1005
1006 done:
1007         slap_sync_cookie_free( &syncCookie, 0 );
1008         slap_sync_cookie_free( &syncCookie_req, 0 );
1009
1010         if ( res ) ldap_msgfree( res );
1011
1012         if ( rc && rc != LDAP_SYNC_REFRESH_REQUIRED && si->si_ld ) {
1013                 if ( si->si_conn_setup ) {
1014                         ber_socket_t s;
1015                         ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1016                         connection_client_stop( s );
1017                         si->si_conn_setup = 0;
1018                 }
1019                 ldap_unbind_ext( si->si_ld, NULL, NULL );
1020                 si->si_ld = NULL;
1021         }
1022
1023         return rc;
1024 }
1025
1026 static void *
1027 do_syncrepl(
1028         void    *ctx,
1029         void    *arg )
1030 {
1031         struct re_s* rtask = arg;
1032         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
1033         Connection conn = {0};
1034         OperationBuffer opbuf;
1035         Operation *op;
1036         int rc = LDAP_SUCCESS;
1037         int dostop = 0;
1038         ber_socket_t s;
1039         int i, defer = 1;
1040         Backend *be;
1041
1042         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
1043
1044         if ( si == NULL )
1045                 return NULL;
1046
1047         ldap_pvt_thread_mutex_lock( &si->si_mutex );
1048
1049         switch( abs( si->si_type )) {
1050         case LDAP_SYNC_REFRESH_ONLY:
1051         case LDAP_SYNC_REFRESH_AND_PERSIST:
1052                 break;
1053         default:
1054                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1055                 return NULL;
1056         }
1057
1058         if ( slapd_shutdown ) {
1059                 if ( si->si_ld ) {
1060                         if ( si->si_conn_setup ) {
1061                                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1062                                 connection_client_stop( s );
1063                                 si->si_conn_setup = 0;
1064                         }
1065                         ldap_unbind_ext( si->si_ld, NULL, NULL );
1066                         si->si_ld = NULL;
1067                 }
1068                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1069                 return NULL;
1070         }
1071
1072         op = (Operation *) &opbuf;
1073         connection_fake_init( &conn, op, ctx );
1074
1075         /* use global malloc for now */
1076         op->o_tmpmemctx = NULL;
1077         op->o_tmpmfuncs = &ch_mfuncs;
1078
1079         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
1080         op->o_bd = be = si->si_be;
1081         op->o_dn = op->o_bd->be_rootdn;
1082         op->o_ndn = op->o_bd->be_rootndn;
1083
1084         /* Establish session, do search */
1085         if ( !si->si_ld ) {
1086                 si->si_refreshDelete = 0;
1087                 si->si_refreshPresent = 0;
1088                 rc = do_syncrep1( op, si );
1089         }
1090
1091 reload:
1092         /* Process results */
1093         if ( rc == LDAP_SUCCESS ) {
1094                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
1095
1096                 rc = do_syncrep2( op, si );
1097                 if ( rc == LDAP_SYNC_REFRESH_REQUIRED ) {
1098                         rc = ldap_sync_search( si, op->o_tmpmemctx );
1099                         goto reload;
1100                 }
1101
1102                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1103                         /* If we succeeded, enable the connection for further listening.
1104                          * If we failed, tear down the connection and reschedule.
1105                          */
1106                         if ( rc == LDAP_SUCCESS ) {
1107                                 if ( si->si_conn_setup ) {
1108                                         connection_client_enable( s );
1109                                 } else {
1110                                         rc = connection_client_setup( s, do_syncrepl, arg );
1111                                         if ( rc == 0 )
1112                                                 si->si_conn_setup = 1;
1113                                 } 
1114                         } else if ( si->si_conn_setup ) {
1115                                 dostop = 1;
1116                         }
1117                 } else {
1118                         if ( rc == -2 ) rc = 0;
1119                 }
1120         }
1121
1122         /* At this point, we have 4 cases:
1123          * 1) for any hard failure, give up and remove this task
1124          * 2) for ServerDown, reschedule this task to run
1125          * 3) for Refresh and Success, reschedule to run
1126          * 4) for Persist and Success, reschedule to defer
1127          */
1128         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
1129
1130         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
1131                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
1132         }
1133
1134         if ( dostop ) {
1135                 connection_client_stop( s );
1136         }
1137
1138         if ( rc == LDAP_SUCCESS ) {
1139                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1140                         defer = 0;
1141                 }
1142                 rtask->interval.tv_sec = si->si_interval;
1143                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1144                 if ( si->si_retrynum ) {
1145                         for ( i = 0; si->si_retrynum_init[i] != RETRYNUM_TAIL; i++ ) {
1146                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1147                         }
1148                         si->si_retrynum[i] = RETRYNUM_TAIL;
1149                 }
1150         } else {
1151                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1152                         if ( si->si_retrynum[i] == RETRYNUM_FOREVER || si->si_retrynum[i] == RETRYNUM_TAIL )
1153                                 break;
1154                 }
1155
1156                 if ( !si->si_retrynum || si->si_retrynum[i] == RETRYNUM_TAIL ) {
1157                         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1158                 } else if ( RETRYNUM_VALID( si->si_retrynum[i] ) ) {
1159                         if ( si->si_retrynum[i] > 0 )
1160                                 si->si_retrynum[i]--;
1161                         rtask->interval.tv_sec = si->si_retryinterval[i];
1162                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1163                         slap_wake_listener();
1164                 }
1165         }
1166         
1167         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1168         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1169
1170         return NULL;
1171 }
1172
1173 static slap_verbmasks modops[] = {
1174         { BER_BVC("add"), LDAP_REQ_ADD },
1175         { BER_BVC("delete"), LDAP_REQ_DELETE },
1176         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1177         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1178         { BER_BVNULL, 0 }
1179 };
1180
1181 static Modifications *
1182 syncrepl_accesslog_mods(
1183         syncinfo_t *si,
1184         struct berval *vals
1185 )
1186 {
1187         char *colon;
1188         const char *text;
1189         AttributeDescription *ad;
1190         struct berval bv, bv2;
1191         short op;
1192         Modifications *mod = NULL, *modlist = NULL, **modtail;
1193         int i;
1194
1195         modtail = &modlist;
1196
1197         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1198                 ad = NULL;
1199                 bv = vals[i];
1200
1201                 colon = ber_bvchr( &bv, ':' );
1202                 if ( !colon )
1203                         continue;       /* invalid */
1204                 bv.bv_len = colon - bv.bv_val;
1205                 if ( slap_bv2ad( &bv, &ad, &text )) {
1206                         /* Invalid */
1207                         continue;
1208                 }
1209                 /* Ignore dynamically generated attrs */
1210                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC )
1211                         continue;
1212                 /* Ignore excluded attrs */
1213                 if ( ldap_charray_inlist( si->si_exattrs,
1214                         ad->ad_type->sat_cname.bv_val ))
1215                         continue;
1216
1217                 switch(colon[1]) {
1218                 case '+':       op = LDAP_MOD_ADD; break;
1219                 case '-':       op = LDAP_MOD_DELETE; break;
1220                 case '=':       op = LDAP_MOD_REPLACE; break;
1221                 case '#':       op = LDAP_MOD_INCREMENT; break;
1222                 default:        continue;
1223                 }
1224
1225                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1226                         mod = (Modifications *) ch_malloc( sizeof( Modifications ));
1227                         mod->sml_flags = 0;
1228                         mod->sml_op = op;
1229                         mod->sml_next = NULL;
1230                         mod->sml_desc = ad;
1231                         mod->sml_type = ad->ad_cname;
1232                         mod->sml_values = NULL;
1233                         mod->sml_nvalues = NULL;
1234
1235                         *modtail = mod;
1236                         modtail = &mod->sml_next;
1237                 }
1238                 if ( colon[2] == ' ' ) {
1239                         bv.bv_val = colon + 3;
1240                         bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1241                         ber_dupbv( &bv2, &bv );
1242                         ber_bvarray_add( &mod->sml_values, &bv2 );
1243                 }
1244         }
1245         return modlist;
1246 }
1247
1248 static Modifications *
1249 syncrepl_changelog_mods(
1250         syncinfo_t *si,
1251         struct berval *vals
1252 )
1253 {
1254         return NULL;    /* FIXME */
1255 }
1256
1257 static int
1258 syncrepl_message_to_op(
1259         syncinfo_t      *si,
1260         Operation       *op,
1261         LDAPMessage     *msg
1262 )
1263 {
1264         BerElement      *ber = NULL;
1265         Modifications   *modlist = NULL;
1266         logschema *ls;
1267         SlapReply rs = { REP_RESULT };
1268         slap_callback cb = { NULL, null_callback, NULL, NULL };
1269
1270         const char      *text;
1271         char txtbuf[SLAP_TEXT_BUFLEN];
1272         size_t textlen = sizeof txtbuf;
1273
1274         struct berval   bdn, dn = BER_BVNULL, ndn;
1275         struct berval   bv, *bvals = NULL;
1276         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1277                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1278                 psup = BER_BVNULL, nsup = BER_BVNULL;
1279         int             rc, deleteOldRdn = 0;
1280
1281         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1282                 Debug( LDAP_DEBUG_ANY,
1283                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1284                 return -1;
1285         }
1286
1287         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1288                 ls = &accesslog_sc;
1289         else
1290                 ls = &changelog_sc;
1291
1292         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1293
1294         if ( rc != LDAP_SUCCESS ) {
1295                 Debug( LDAP_DEBUG_ANY,
1296                         "syncrepl_message_to_op : dn get failed (%d)", rc, 0, 0 );
1297                 return rc;
1298         }
1299
1300         op->o_tag = LBER_DEFAULT;
1301
1302         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ))
1303                 == LDAP_SUCCESS ) {
1304                 if ( bv.bv_val == NULL )
1305                         break;
1306
1307                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn )) {
1308                         bdn = bvals[0];
1309                         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1310                         ber_dupbv( &op->o_req_dn, &dn );
1311                         ber_dupbv( &op->o_req_ndn, &ndn );
1312                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1313                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1314                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req )) {
1315                         int i = verb_to_mask( bvals[0].bv_val, modops );
1316                         if ( i < 0 ) {
1317                                 Debug( LDAP_DEBUG_ANY,
1318                                         "syncrepl_message_to_op : unknown op %s",
1319                                         bvals[0].bv_val, 0, 0 );
1320                                 ch_free( bvals );
1321                                 rc = -1;
1322                                 goto done;
1323                         }
1324                         op->o_tag = modops[i].mask;
1325                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod )) {
1326                         /* Parse attribute into modlist */
1327                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1328                                 modlist = syncrepl_accesslog_mods( si, bvals );
1329                         else
1330                                 modlist = syncrepl_changelog_mods( si, bvals );
1331                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn )) {
1332                         rdn = bvals[0];
1333                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn )) {
1334                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ))
1335                                 deleteOldRdn = 1;
1336                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup )) {
1337                         sup = bvals[0];
1338                 } else if ( !ber_bvstrcasecmp( &bv,
1339                         &slap_schema.si_ad_entryCSN->ad_cname )) {
1340                         slap_queue_csn( op, bvals );
1341                 }
1342                 ch_free( bvals );
1343         }
1344
1345         /* If we didn't get a mod type or a target DN, bail out */
1346         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn )) {
1347                 rc = -1;
1348                 goto done;
1349         }
1350
1351         op->o_callback = &cb;
1352
1353         switch( op->o_tag ) {
1354         case LDAP_REQ_ADD:
1355         case LDAP_REQ_MODIFY:
1356                 /* If we didn't get required data, bail */
1357                 if ( !modlist ) goto done;
1358
1359                 rc = slap_mods_check( modlist, &text, txtbuf, textlen, NULL );
1360
1361                 if ( rc != LDAP_SUCCESS ) {
1362                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: mods check (%s)\n",
1363                                 text, 0, 0 );
1364                         goto done;
1365                 }
1366
1367                 if ( op->o_tag == LDAP_REQ_ADD ) {
1368                         op->ora_e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1369                         op->ora_e->e_name = op->o_req_dn;
1370                         op->ora_e->e_nname = op->o_req_ndn;
1371                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1372                         if( rc != LDAP_SUCCESS ) {
1373                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: mods2entry (%s)\n",
1374                                         text, 0, 0 );
1375                         } else {
1376                                 rc = op->o_bd->be_add( op, &rs );
1377                                 Debug( LDAP_DEBUG_SYNC,
1378                                         "syncrepl_message_to_op: be_add %s (%d)\n", 
1379                                         op->o_req_dn.bv_val, rc, 0 );
1380                         }
1381                         be_entry_release_w( op, op->ora_e );
1382                 } else {
1383                         op->orm_modlist = modlist;
1384                         rc = op->o_bd->be_modify( op, &rs );
1385                         Debug( LDAP_DEBUG_SYNC,
1386                                 "syncrepl_message_to_op: be_modify %s (%d)\n", 
1387                                 op->o_req_dn.bv_val, rc, 0 );
1388                 }
1389                 break;
1390         case LDAP_REQ_MODRDN:
1391                 if ( BER_BVISNULL( &rdn )) goto done;
1392
1393                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ))
1394                         goto done;
1395                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ))
1396                         goto done;
1397                 if ( !BER_BVISNULL( &sup )) {
1398                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ))
1399                                 goto done;
1400                         op->orr_newSup = &psup;
1401                         op->orr_nnewSup = &nsup;
1402                 }
1403                 op->orr_newrdn = prdn;
1404                 op->orr_nnewrdn = nrdn;
1405                 op->orr_deleteoldrdn = deleteOldRdn;
1406                 op->orr_modlist = NULL;
1407                 if ( slap_modrdn2mods( op, &rs ))
1408                         goto done;
1409                 rc = op->o_bd->be_modrdn( op, &rs );
1410                 slap_mods_free( op->orr_modlist, 1 );
1411                 Debug( LDAP_DEBUG_SYNC,
1412                         "syncrepl_message_to_op: be_modrdn %s (%d)\n", 
1413                         op->o_req_dn.bv_val, rc, 0 );
1414                 break;
1415         case LDAP_REQ_DELETE:
1416                 rc = op->o_bd->be_delete( op, &rs );
1417                 Debug( LDAP_DEBUG_SYNC,
1418                         "syncrepl_message_to_op: be_delete %s (%d)\n", 
1419                         op->o_req_dn.bv_val, rc, 0 );
1420                 break;
1421         }
1422 done:
1423         slap_graduate_commit_csn( op );
1424         if ( modlist )
1425                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1426         if ( !BER_BVISNULL( &rdn )) {
1427                 if ( !BER_BVISNULL( &nsup ))
1428                         ch_free( nsup.bv_val );
1429                 if ( !BER_BVISNULL( &psup ))
1430                         ch_free( psup.bv_val );
1431                 if ( !BER_BVISNULL( &nrdn ))
1432                         ch_free( nrdn.bv_val );
1433                 if ( !BER_BVISNULL( &prdn ))
1434                         ch_free( prdn.bv_val );
1435         }
1436         ber_free ( ber, 0 );
1437         return rc;
1438 }
1439
1440 static int
1441 syncrepl_message_to_entry(
1442         syncinfo_t      *si,
1443         Operation       *op,
1444         LDAPMessage     *msg,
1445         Modifications   **modlist,
1446         Entry                   **entry,
1447         int             syncstate
1448 )
1449 {
1450         Entry           *e = NULL;
1451         BerElement      *ber = NULL;
1452         Modifications   tmp;
1453         Modifications   *mod;
1454         Modifications   **modtail = modlist;
1455
1456         const char      *text;
1457         char txtbuf[SLAP_TEXT_BUFLEN];
1458         size_t textlen = sizeof txtbuf;
1459
1460         struct berval   bdn = {0, NULL}, dn, ndn;
1461         int             rc;
1462
1463         *modlist = NULL;
1464
1465         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1466                 Debug( LDAP_DEBUG_ANY,
1467                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1468                 return -1;
1469         }
1470
1471         op->o_tag = LDAP_REQ_ADD;
1472
1473         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1474
1475         if ( rc != LDAP_SUCCESS ) {
1476                 Debug( LDAP_DEBUG_ANY,
1477                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1478                 return rc;
1479         }
1480
1481         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1482         ber_dupbv( &op->o_req_dn, &dn );
1483         ber_dupbv( &op->o_req_ndn, &ndn );
1484         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1485         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1486
1487         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1488                 if ( entry )
1489                         *entry = NULL;
1490                 return LDAP_SUCCESS;
1491         }
1492
1493         if ( entry == NULL ) {
1494                 return -1;
1495         }
1496
1497         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1498         e->e_name = op->o_req_dn;
1499         e->e_nname = op->o_req_ndn;
1500
1501         while ( ber_remaining( ber ) ) {
1502                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1503                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1504                 {
1505                         break;
1506                 }
1507
1508                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1509
1510                 mod->sml_op = LDAP_MOD_REPLACE;
1511                 mod->sml_flags = 0;
1512                 mod->sml_next = NULL;
1513                 mod->sml_desc = NULL;
1514                 mod->sml_type = tmp.sml_type;
1515                 mod->sml_values = tmp.sml_values;
1516                 mod->sml_nvalues = NULL;
1517
1518                 *modtail = mod;
1519                 modtail = &mod->sml_next;
1520         }
1521
1522         if ( *modlist == NULL ) {
1523                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1524                         0, 0, 0 );
1525                 rc = -1;
1526                 goto done;
1527         }
1528
1529         rc = slap_mods_check( *modlist, &text, txtbuf, textlen, NULL );
1530
1531         if ( rc != LDAP_SUCCESS ) {
1532                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1533                         text, 0, 0 );
1534                 goto done;
1535         }
1536
1537         /* Strip out dynamically generated attrs */
1538         for ( modtail = modlist; *modtail ; ) {
1539                 mod = *modtail;
1540                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1541                         *modtail = mod->sml_next;
1542                         slap_mod_free( &mod->sml_mod, 0 );
1543                         ch_free( mod );
1544                 } else {
1545                         modtail = &mod->sml_next;
1546                 }
1547         }
1548
1549         /* Strip out attrs in exattrs list */
1550         for ( modtail = modlist; *modtail ; ) {
1551                 mod = *modtail;
1552                 if ( ldap_charray_inlist( si->si_exattrs,
1553                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1554                         *modtail = mod->sml_next;
1555                         slap_mod_free( &mod->sml_mod, 0 );
1556                         ch_free( mod );
1557                 } else {
1558                         modtail = &mod->sml_next;
1559                 }
1560         }
1561         
1562         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1563         if( rc != LDAP_SUCCESS ) {
1564                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1565                         text, 0, 0 );
1566         }
1567
1568 done:
1569         ber_free ( ber, 0 );
1570         if ( rc != LDAP_SUCCESS ) {
1571                 if ( e ) {
1572                         entry_free( e );
1573                         e = NULL;
1574                 }
1575         }
1576         *entry = e;
1577
1578         return rc;
1579 }
1580
1581 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1582
1583 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1584  * entry if a previous refresh was interrupted before sending us a new
1585  * context state. We try to compare the new entry to the existing entry
1586  * and ignore the new entry if they are the same.
1587  *
1588  * Also, we may get an update where the entryDN has changed, due to
1589  * a ModDn on the provider. We detect this as well, so we can issue
1590  * the corresponding operation locally.
1591  *
1592  * In the case of a modify, we get a list of all the attributes
1593  * in the original entry. Rather than deleting the entry and re-adding it,
1594  * we issue a Modify request that deletes all the attributes and adds all
1595  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1596  * entry.
1597  *
1598  * We don't try to otherwise distinguish ModDN from Modify; in the case of
1599  * a ModDN we will issue both operations on the local database.
1600  */
1601 typedef struct dninfo {
1602         Entry *new_entry;
1603         struct berval dn;
1604         struct berval ndn;
1605         int renamed;    /* Was an existing entry renamed? */
1606         int wasChanged; /* are the attributes changed? */
1607         int attrs;              /* how many attribute types are in the ads list */
1608         AttributeDescription **ads;
1609 } dninfo;
1610
1611 static int
1612 syncrepl_entry(
1613         syncinfo_t* si,
1614         Operation *op,
1615         Entry* entry,
1616         Modifications** modlist,
1617         int syncstate,
1618         struct berval* syncUUID,
1619         struct sync_cookie* syncCookie_req,
1620         struct berval* syncCSN )
1621 {
1622         Backend *be = op->o_bd;
1623         slap_callback   cb = { NULL, NULL, NULL, NULL };
1624         struct berval   *syncuuid_bv = NULL;
1625         struct berval   syncUUID_strrep = BER_BVNULL;
1626         struct berval   uuid_bv = BER_BVNULL;
1627
1628         SlapReply       rs_search = {REP_RESULT};
1629         SlapReply       rs_delete = {REP_RESULT};
1630         SlapReply       rs_add = {REP_RESULT};
1631         SlapReply       rs_modify = {REP_RESULT};
1632         Filter f = {0};
1633 #ifdef LDAP_COMP_MATCH
1634         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1635 #else
1636         AttributeAssertion ava = { NULL, BER_BVNULL };
1637 #endif
1638         int rc = LDAP_SUCCESS;
1639
1640         struct berval pdn = BER_BVNULL;
1641         dninfo dni = {0};
1642         int     retry = 1;
1643
1644         switch( syncstate ) {
1645         case LDAP_SYNC_PRESENT:
1646                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1647                                         "syncrepl_entry",
1648                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1649                 break;
1650         case LDAP_SYNC_ADD:
1651                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1652                                         "syncrepl_entry",
1653                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1654                 break;
1655         case LDAP_SYNC_DELETE:
1656                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1657                                         "syncrepl_entry",
1658                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1659                 break;
1660         case LDAP_SYNC_MODIFY:
1661                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1662                                         "syncrepl_entry",
1663                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1664                 break;
1665         default:
1666                 Debug( LDAP_DEBUG_ANY, "%s: %s\n",
1667                                         "syncrepl_entry",
1668                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1669         }
1670
1671         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1672                 if ( !si->si_refreshPresent ) {
1673                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1674                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1675                                 syncuuid_cmp, avl_dup_error );
1676                 }
1677         }
1678
1679         if ( syncstate == LDAP_SYNC_PRESENT ) {
1680                 return 0;
1681         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1682                 if ( entry == NULL ) {
1683                         return 0;
1684                 }
1685         }
1686
1687         f.f_choice = LDAP_FILTER_EQUALITY;
1688         f.f_ava = &ava;
1689         ava.aa_desc = slap_schema.si_ad_entryUUID;
1690         ava.aa_value = *syncUUID;
1691
1692         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1693         if ( syncuuid_bv ) {
1694                 Debug( LDAP_DEBUG_SYNC, "syncrepl_entry: inserted UUID %s\n",
1695                         syncUUID_strrep.bv_val, 0, 0 );
1696         }
1697         op->ors_filter = &f;
1698
1699         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID_strrep.bv_len;
1700         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1701                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1702         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1703         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1704                 syncUUID_strrep.bv_val, syncUUID_strrep.bv_len );
1705         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1706         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1707
1708         op->o_tag = LDAP_REQ_SEARCH;
1709         op->ors_scope = LDAP_SCOPE_SUBTREE;
1710         op->ors_deref = LDAP_DEREF_NEVER;
1711
1712         /* get the entry for this UUID */
1713         op->o_req_dn = si->si_base;
1714         op->o_req_ndn = si->si_base;
1715
1716         op->o_time = slap_get_time();
1717         op->ors_tlimit = SLAP_NO_LIMIT;
1718         op->ors_slimit = 1;
1719
1720         op->ors_attrs = slap_anlist_all_attributes;
1721         op->ors_attrsonly = 0;
1722
1723         /* set callback function */
1724         op->o_callback = &cb;
1725         cb.sc_response = dn_callback;
1726         cb.sc_private = &dni;
1727         dni.new_entry = entry;
1728
1729         if ( limits_check( op, &rs_search ) == 0 ) {
1730                 rc = be->be_search( op, &rs_search );
1731                 Debug( LDAP_DEBUG_SYNC,
1732                                 "syncrepl_entry: %s (%d)\n", 
1733                                 "be_search", rc, 0 );
1734         }
1735
1736         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1737                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1738         }
1739
1740         cb.sc_response = null_callback;
1741         cb.sc_private = si;
1742
1743         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1744                 Debug( LDAP_DEBUG_SYNC,
1745                                 "syncrepl_entry: %s\n",
1746                                 entry->e_name.bv_val, 0, 0 );
1747         } else {
1748                 Debug( LDAP_DEBUG_SYNC,
1749                                 "syncrepl_entry: %s\n",
1750                                 dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0, 0 );
1751         }
1752
1753         if ( syncstate != LDAP_SYNC_DELETE ) {
1754                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1755
1756                 if ( a == NULL ) {
1757                         /* add if missing */
1758                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1759                                 &syncUUID_strrep, syncUUID );
1760
1761                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1762                         /* replace only if necessary */
1763                         if ( a->a_nvals != a->a_vals ) {
1764                                 ber_memfree( a->a_nvals[0].bv_val );
1765                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1766                         }
1767                         ber_memfree( a->a_vals[0].bv_val );
1768                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1769                 }
1770         }
1771
1772         switch ( syncstate ) {
1773         case LDAP_SYNC_ADD:
1774         case LDAP_SYNC_MODIFY:
1775                 {
1776                         Attribute *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryCSN );
1777                         if ( a ) {
1778                                 /* FIXME: op->o_csn is assumed to be
1779                                  * on the thread's slab; this needs
1780                                  * to be cleared ASAP.
1781                                  * What happens if already present?
1782                                  */
1783                                 assert( BER_BVISNULL( &op->o_csn ) );
1784                                 op->o_csn = a->a_vals[0];
1785                         }
1786                 }
1787 retry_add:;
1788                 if ( BER_BVISNULL( &dni.dn )) {
1789
1790                         op->o_req_dn = entry->e_name;
1791                         op->o_req_ndn = entry->e_nname;
1792                         op->o_tag = LDAP_REQ_ADD;
1793                         op->ora_e = entry;
1794
1795                         rc = be->be_add( op, &rs_add );
1796                         Debug( LDAP_DEBUG_SYNC,
1797                                         "syncrepl_entry: %s (%d)\n", 
1798                                         "be_add", rc, 0 );
1799                         switch ( rs_add.sr_err ) {
1800                         case LDAP_SUCCESS:
1801                                 be_entry_release_w( op, entry );
1802                                 entry = NULL;
1803                                 break;
1804
1805                         case LDAP_REFERRAL:
1806                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1807                          * only if the suffix entry is not present */
1808                         case LDAP_NO_SUCH_OBJECT:
1809                                 rc = syncrepl_add_glue( op, entry );
1810                                 entry = NULL;
1811                                 break;
1812
1813                         /* if an entry was added via syncrepl_add_glue(),
1814                          * it likely has no entryUUID, so the previous
1815                          * be_search() doesn't find it.  In this case,
1816                          * give syncrepl a chance to modify it. Also
1817                          * allow for entries that were recreated with the
1818                          * same DN but a different entryUUID.
1819                          */
1820                         case LDAP_ALREADY_EXISTS:
1821                                 if ( retry ) {
1822                                         Operation       op2 = *op;
1823                                         SlapReply       rs2 = { 0 };
1824                                         slap_callback   cb2 = { 0 };
1825
1826                                         op2.o_tag = LDAP_REQ_SEARCH;
1827                                         op2.o_req_dn = entry->e_name;
1828                                         op2.o_req_ndn = entry->e_nname;
1829                                         op2.ors_scope = LDAP_SCOPE_BASE;
1830                                         op2.ors_deref = LDAP_DEREF_NEVER;
1831                                         op2.ors_attrs = slap_anlist_all_attributes;
1832                                         op2.ors_attrsonly = 0;
1833                                         op2.ors_limit = NULL;
1834                                         op2.ors_slimit = 1;
1835                                         op2.ors_tlimit = SLAP_NO_LIMIT;
1836
1837                                         f.f_choice = LDAP_FILTER_PRESENT;
1838                                         f.f_desc = slap_schema.si_ad_objectClass;
1839                                         op2.ors_filter = &f;
1840                                         op2.ors_filterstr = generic_filterstr;
1841
1842                                         op2.o_callback = &cb2;
1843                                         cb2.sc_response = dn_callback;
1844                                         cb2.sc_private = &dni;
1845
1846                                         rc = be->be_search( &op2, &rs2 );
1847                                         if ( rc ) goto done;
1848
1849                                         retry = 0;
1850                                         goto retry_add;
1851                                 }
1852                                 /* FALLTHRU */
1853
1854                         default:
1855                                 Debug( LDAP_DEBUG_ANY,
1856                                         "syncrepl_entry : be_add failed (%d)\n",
1857                                         rs_add.sr_err, 0, 0 );
1858                                 break;
1859                         }
1860                         goto done;
1861                 }
1862                 /* FALLTHRU */
1863                 op->o_req_dn = dni.dn;
1864                 op->o_req_ndn = dni.ndn;
1865                 if ( dni.renamed ) {
1866                         struct berval noldp, newp, nnewp;
1867
1868                         op->o_tag = LDAP_REQ_MODRDN;
1869                         dnRdn( &entry->e_name, &op->orr_newrdn );
1870                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
1871
1872                         dnParent( &dni.ndn, &noldp );
1873                         dnParent( &entry->e_nname, &nnewp );
1874                         if ( !dn_match( &noldp, &nnewp )) {
1875                                 dnParent( &entry->e_name, &newp );
1876                                 op->orr_newSup = &newp;
1877                                 op->orr_nnewSup = &nnewp;
1878                         }
1879                         op->orr_deleteoldrdn = 0;
1880                         op->orr_modlist = NULL;
1881                         if (( rc = slap_modrdn2mods( op, &rs_modify ))) {
1882                                 goto done;
1883                         }
1884                         rc = be->be_modrdn( op, &rs_modify );
1885                         slap_mods_free( op->orr_modlist, 1 );
1886                         Debug( LDAP_DEBUG_SYNC,
1887                                         "syncrepl_entry: %s (%d)\n", 
1888                                         "be_modrdn", rc, 0 );
1889                         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
1890                                 op->o_req_dn = entry->e_name;
1891                                 op->o_req_ndn = entry->e_nname;
1892                         } else {
1893                                 goto done;
1894                         }
1895                 }
1896                 if ( dni.wasChanged ) {
1897                         Modifications *mod, *modhead = NULL;
1898                         Modifications *modtail = NULL;
1899                         int i;
1900
1901                         op->o_tag = LDAP_REQ_MODIFY;
1902
1903                         assert( *modlist != NULL );
1904
1905                         /* Delete all the old attrs */
1906                         for ( i = 0; i < dni.attrs; i++ ) {
1907                                 mod = ch_malloc( sizeof( Modifications ) );
1908                                 mod->sml_op = LDAP_MOD_DELETE;
1909                                 mod->sml_flags = 0;
1910                                 mod->sml_desc = dni.ads[i];
1911                                 mod->sml_type = mod->sml_desc->ad_cname;
1912                                 mod->sml_values = NULL;
1913                                 mod->sml_nvalues = NULL;
1914                                 if ( !modhead ) modhead = mod;
1915                                 if ( modtail ) {
1916                                         modtail->sml_next = mod;
1917                                 }
1918                                 modtail = mod;
1919                         }
1920
1921                         /* Append passed in list to ours */
1922                         if ( modtail ) {
1923                                 modtail->sml_next = *modlist;
1924                                 *modlist = modhead;
1925                         } else {
1926                                 mod = *modlist;
1927                         }
1928
1929                         /* Find end of this list */
1930                         for ( ; mod != NULL; mod = mod->sml_next ) {
1931                                 modtail = mod;
1932                         }
1933
1934                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1935                         mod->sml_op = LDAP_MOD_REPLACE;
1936                         mod->sml_flags = 0;
1937                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1938                         mod->sml_type = mod->sml_desc->ad_cname;
1939                         ber_dupbv( &uuid_bv, &syncUUID_strrep );
1940                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1941                         ber_dupbv( &uuid_bv, syncUUID );
1942                         ber_bvarray_add( &mod->sml_nvalues, &uuid_bv );
1943                         modtail->sml_next = mod;
1944                                         
1945                         op->o_tag = LDAP_REQ_MODIFY;
1946                         op->orm_modlist = *modlist;
1947
1948                         rc = be->be_modify( op, &rs_modify );
1949                         Debug( LDAP_DEBUG_SYNC,
1950                                         "syncrepl_entry: %s (%d)\n", 
1951                                         "be_modify", rc, 0 );
1952                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1953                                 Debug( LDAP_DEBUG_ANY,
1954                                         "syncrepl_entry : be_modify failed (%d)\n",
1955                                         rs_modify.sr_err, 0, 0 );
1956                         }
1957                 }
1958                 goto done;
1959         case LDAP_SYNC_DELETE :
1960                 if ( !BER_BVISNULL( &dni.dn )) {
1961                         op->o_req_dn = dni.dn;
1962                         op->o_req_ndn = dni.ndn;
1963                         op->o_tag = LDAP_REQ_DELETE;
1964                         rc = be->be_delete( op, &rs_delete );
1965                         Debug( LDAP_DEBUG_SYNC,
1966                                         "syncrepl_entry: %s (%d)\n", 
1967                                         "be_delete", rc, 0 );
1968
1969                         while ( rs_delete.sr_err == LDAP_SUCCESS
1970                                 && op->o_delete_glue_parent ) {
1971                                 op->o_delete_glue_parent = 0;
1972                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1973                                         slap_callback cb = { NULL };
1974                                         cb.sc_response = slap_null_cb;
1975                                         dnParent( &op->o_req_ndn, &pdn );
1976                                         op->o_req_dn = pdn;
1977                                         op->o_req_ndn = pdn;
1978                                         op->o_callback = &cb;
1979                                         op->o_bd->be_delete( op, &rs_delete );
1980                                 } else {
1981                                         break;
1982                                 }
1983                         }
1984                 }
1985                 goto done;
1986
1987         default :
1988                 Debug( LDAP_DEBUG_ANY,
1989                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1990                 goto done;
1991         }
1992
1993 done:
1994         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
1995                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1996                 BER_BVZERO( &syncUUID_strrep );
1997         }
1998         if ( dni.ads ) {
1999                 op->o_tmpfree( dni.ads, op->o_tmpmemctx );
2000         }
2001         if ( !BER_BVISNULL( &dni.ndn ) ) {
2002                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
2003         }
2004         if ( !BER_BVISNULL( &dni.dn ) ) {
2005                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
2006         }
2007         if ( entry )
2008                 entry_free( entry );
2009         BER_BVZERO( &op->o_csn );
2010         return rc;
2011 }
2012
2013 static struct berval gcbva[] = {
2014         BER_BVC("top"),
2015         BER_BVC("glue"),
2016         BER_BVNULL
2017 };
2018
2019 #define NP_DELETE_ONE   2
2020
2021 static void
2022 syncrepl_del_nonpresent(
2023         Operation *op,
2024         syncinfo_t *si,
2025         BerVarray uuids )
2026 {
2027         Backend* be = op->o_bd;
2028         slap_callback   cb = { NULL };
2029         SlapReply       rs_search = {REP_RESULT};
2030         SlapReply       rs_delete = {REP_RESULT};
2031         SlapReply       rs_modify = {REP_RESULT};
2032         struct nonpresent_entry *np_list, *np_prev;
2033         int rc;
2034         AttributeName   an[2];
2035
2036         struct berval pdn = BER_BVNULL;
2037
2038         op->o_req_dn = si->si_base;
2039         op->o_req_ndn = si->si_base;
2040
2041         cb.sc_response = nonpresent_callback;
2042         cb.sc_private = si;
2043
2044         op->o_callback = &cb;
2045         op->o_tag = LDAP_REQ_SEARCH;
2046         op->ors_scope = si->si_scope;
2047         op->ors_deref = LDAP_DEREF_NEVER;
2048         op->o_time = slap_get_time();
2049         op->ors_tlimit = SLAP_NO_LIMIT;
2050
2051
2052         if ( uuids ) {
2053                 Filter uf;
2054 #ifdef LDAP_COMP_MATCH
2055                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
2056 #else
2057                 AttributeAssertion eq = { NULL, BER_BVNULL };
2058 #endif
2059                 int i;
2060
2061                 op->ors_attrsonly = 1;
2062                 op->ors_attrs = slap_anlist_no_attrs;
2063                 op->ors_limit = NULL;
2064                 op->ors_filter = &uf;
2065
2066                 uf.f_ava = &eq;
2067                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
2068                 uf.f_next = NULL;
2069                 uf.f_choice = LDAP_FILTER_EQUALITY;
2070                 si->si_refreshDelete |= NP_DELETE_ONE;
2071
2072                 for (i=0; uuids[i].bv_val; i++) {
2073                         op->ors_slimit = 1;
2074                         slap_uuidstr_from_normalized( &uf.f_av_value, &uuids[i],
2075                                 op->o_tmpmemctx );
2076                         filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
2077                         uf.f_av_value = uuids[i];
2078                         rc = be->be_search( op, &rs_search );
2079                         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
2080                 }
2081                 si->si_refreshDelete ^= NP_DELETE_ONE;
2082         } else {
2083                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
2084                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
2085                 an[0].an_desc = slap_schema.si_ad_entryUUID;
2086                 op->ors_attrs = an;
2087                 op->ors_slimit = SLAP_NO_LIMIT;
2088                 op->ors_attrsonly = 0;
2089                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
2090                 op->ors_filterstr = si->si_filterstr;
2091                 op->o_nocaching = 1;
2092
2093                 if ( limits_check( op, &rs_search ) == 0 ) {
2094                         rc = be->be_search( op, &rs_search );
2095                 }
2096                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
2097         }
2098
2099         op->o_nocaching = 0;
2100
2101         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
2102
2103                 slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
2104
2105                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
2106                 while ( np_list != NULL ) {
2107                         LDAP_LIST_REMOVE( np_list, npe_link );
2108                         np_prev = np_list;
2109                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
2110                         op->o_tag = LDAP_REQ_DELETE;
2111                         op->o_callback = &cb;
2112                         cb.sc_response = null_callback;
2113                         cb.sc_private = si;
2114                         op->o_req_dn = *np_prev->npe_name;
2115                         op->o_req_ndn = *np_prev->npe_nname;
2116                         rc = op->o_bd->be_delete( op, &rs_delete );
2117                         Debug( LDAP_DEBUG_SYNC,
2118                                 "syncrepl_del_nonpresent: be_delete %s (%d)\n", 
2119                                 op->o_req_dn.bv_val, rc, 0 );
2120
2121                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
2122                                 Modifications mod1, mod2;
2123                                 mod1.sml_op = LDAP_MOD_REPLACE;
2124                                 mod1.sml_flags = 0;
2125                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
2126                                 mod1.sml_type = mod1.sml_desc->ad_cname;
2127                                 mod1.sml_values = &gcbva[0];
2128                                 mod1.sml_nvalues = NULL;
2129                                 mod1.sml_next = &mod2;
2130
2131                                 mod2.sml_op = LDAP_MOD_REPLACE;
2132                                 mod2.sml_flags = 0;
2133                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
2134                                 mod2.sml_type = mod2.sml_desc->ad_cname;
2135                                 mod2.sml_values = &gcbva[1];
2136                                 mod2.sml_nvalues = NULL;
2137                                 mod2.sml_next = NULL;
2138
2139                                 op->o_tag = LDAP_REQ_MODIFY;
2140                                 op->orm_modlist = &mod1;
2141
2142                                 rc = be->be_modify( op, &rs_modify );
2143                         }
2144
2145                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
2146                                         op->o_delete_glue_parent ) {
2147                                 op->o_delete_glue_parent = 0;
2148                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
2149                                         slap_callback cb = { NULL };
2150                                         cb.sc_response = slap_null_cb;
2151                                         dnParent( &op->o_req_ndn, &pdn );
2152                                         op->o_req_dn = pdn;
2153                                         op->o_req_ndn = pdn;
2154                                         op->o_callback = &cb;
2155                                         /* give it a root privil ? */
2156                                         op->o_bd->be_delete( op, &rs_delete );
2157                                 } else {
2158                                         break;
2159                             }
2160                         }
2161
2162                         op->o_delete_glue_parent = 0;
2163
2164                         ber_bvfree( np_prev->npe_name );
2165                         ber_bvfree( np_prev->npe_nname );
2166                         ch_free( np_prev );
2167                 }
2168
2169                 slap_graduate_commit_csn( op );
2170
2171                 op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2172                 BER_BVZERO( &op->o_csn );
2173         }
2174
2175         return;
2176 }
2177
2178 int
2179 syncrepl_add_glue(
2180         Operation* op,
2181         Entry *e )
2182 {
2183         Backend *be = op->o_bd;
2184         slap_callback cb = { NULL };
2185         Attribute       *a;
2186         int     rc;
2187         int suffrdns;
2188         int i;
2189         struct berval dn = BER_BVNULL;
2190         struct berval ndn = BER_BVNULL;
2191         Entry   *glue;
2192         SlapReply       rs_add = {REP_RESULT};
2193         struct berval   ptr, nptr;
2194         char            *comma;
2195
2196         op->o_tag = LDAP_REQ_ADD;
2197         op->o_callback = &cb;
2198         cb.sc_response = null_callback;
2199         cb.sc_private = NULL;
2200
2201         dn = e->e_name;
2202         ndn = e->e_nname;
2203
2204         /* count RDNs in suffix */
2205         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2206                 for ( i = 0, ptr = be->be_nsuffix[0], comma = ptr.bv_val; comma != NULL; comma = ber_bvchr( &ptr, ',' ) ) {
2207                         comma++;
2208                         ptr.bv_len -= comma - ptr.bv_val;
2209                         ptr.bv_val = comma;
2210                         i++;
2211                 }
2212                 suffrdns = i;
2213         } else {
2214                 /* suffix is "" */
2215                 suffrdns = 0;
2216         }
2217
2218         /* Start with BE suffix */
2219         ptr = dn;
2220         for ( i = 0; i < suffrdns; i++ ) {
2221                 comma = ber_bvrchr( &ptr, ',' );
2222                 if ( comma != NULL ) {
2223                         ptr.bv_len = comma - ptr.bv_val;
2224                 } else {
2225                         ptr.bv_len = 0;
2226                         break;
2227                 }
2228         }
2229         
2230         if ( !BER_BVISEMPTY( &ptr ) ) {
2231                 dn.bv_len -= ptr.bv_len + 1;
2232                 dn.bv_val += ptr.bv_len + 1;
2233         }
2234
2235         /* the normalizedDNs are always the same length, no counting
2236          * required.
2237          */
2238         nptr = ndn;
2239         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2240                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2241                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2242
2243                 nptr.bv_len = ndn.bv_val - nptr.bv_val - 1;
2244
2245         } else {
2246                 nptr.bv_len = 0;
2247         }
2248
2249         while ( ndn.bv_val > e->e_nname.bv_val ) {
2250                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
2251                 ber_dupbv( &glue->e_name, &dn );
2252                 ber_dupbv( &glue->e_nname, &ndn );
2253
2254                 a = ch_calloc( 1, sizeof( Attribute ));
2255                 a->a_desc = slap_schema.si_ad_objectClass;
2256
2257                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
2258                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2259                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2260                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2261
2262                 a->a_nvals = a->a_vals;
2263
2264                 a->a_next = glue->e_attrs;
2265                 glue->e_attrs = a;
2266
2267                 a = ch_calloc( 1, sizeof( Attribute ));
2268                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
2269
2270                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
2271                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2272                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2273
2274                 a->a_nvals = a->a_vals;
2275
2276                 a->a_next = glue->e_attrs;
2277                 glue->e_attrs = a;
2278
2279                 op->o_req_dn = glue->e_name;
2280                 op->o_req_ndn = glue->e_nname;
2281                 op->ora_e = glue;
2282                 rc = be->be_add ( op, &rs_add );
2283                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2284                         be_entry_release_w( op, glue );
2285                 } else {
2286                 /* incl. ALREADY EXIST */
2287                         entry_free( glue );
2288                         if ( rs_add.sr_err != LDAP_ALREADY_EXISTS ) {
2289                                 entry_free( e );
2290                                 return rc;
2291                         }
2292                 }
2293
2294                 /* Move to next child */
2295                 comma = ber_bvrchr( &ptr, ',' );
2296                 if ( comma == NULL ) {
2297                         break;
2298                 }
2299                 ptr.bv_len = comma - ptr.bv_val;
2300                 
2301                 dn.bv_val = ++comma;
2302                 dn.bv_len = e->e_name.bv_len - (dn.bv_val - e->e_name.bv_val);
2303
2304                 comma = ber_bvrchr( &nptr, ',' );
2305                 assert( comma != NULL );
2306                 nptr.bv_len = comma - nptr.bv_val;
2307
2308                 ndn.bv_val = ++comma;
2309                 ndn.bv_len = e->e_nname.bv_len - (ndn.bv_val - e->e_nname.bv_val);
2310         }
2311
2312         op->o_req_dn = e->e_name;
2313         op->o_req_ndn = e->e_nname;
2314         op->ora_e = e;
2315         rc = be->be_add ( op, &rs_add );
2316         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2317                 be_entry_release_w( op, e );
2318         } else {
2319                 entry_free( e );
2320         }
2321
2322         return rc;
2323 }
2324
2325 static int
2326 syncrepl_updateCookie(
2327         syncinfo_t *si,
2328         Operation *op,
2329         struct berval *pdn,
2330         struct sync_cookie *syncCookie )
2331 {
2332         Backend *be = op->o_bd;
2333         Modifications mod = { { 0 } };
2334         struct berval vals[ 2 ];
2335
2336         int rc;
2337
2338         slap_callback cb = { NULL };
2339         SlapReply       rs_modify = {REP_RESULT};
2340
2341         mod.sml_op = LDAP_MOD_REPLACE;
2342         mod.sml_desc = slap_schema.si_ad_contextCSN;
2343         mod.sml_type = mod.sml_desc->ad_cname;
2344         mod.sml_values = vals;
2345         vals[0] = syncCookie->ctxcsn;
2346         BER_BVZERO( &vals[1] );
2347
2348         slap_queue_csn( op, &syncCookie->ctxcsn );
2349
2350         op->o_tag = LDAP_REQ_MODIFY;
2351
2352         assert( si->si_rid < 1000 );
2353
2354         cb.sc_response = null_callback;
2355         cb.sc_private = si;
2356
2357         op->o_callback = &cb;
2358         op->o_req_dn = op->o_bd->be_suffix[0];
2359         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2360
2361         /* update contextCSN */
2362         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2363         op->orm_modlist = &mod;
2364         rc = be->be_modify( op, &rs_modify );
2365         op->o_msgid = 0;
2366
2367         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
2368                 slap_sync_cookie_free( &si->si_syncCookie, 0 );
2369                 slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2370         } else {
2371                 Debug( LDAP_DEBUG_ANY,
2372                         "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
2373         }
2374
2375         slap_graduate_commit_csn( op );
2376
2377         op->o_tmpfree( op->o_csn.bv_val, op->o_tmpmemctx );
2378         BER_BVZERO( &op->o_csn );
2379
2380         return rc;
2381 }
2382
2383 static int
2384 dn_callback(
2385         Operation*      op,
2386         SlapReply*      rs )
2387 {
2388         dninfo *dni = op->o_callback->sc_private;
2389
2390         if ( rs->sr_type == REP_SEARCH ) {
2391                 if ( !BER_BVISNULL( &dni->dn ) ) {
2392                         Debug( LDAP_DEBUG_ANY,
2393                                 "dn_callback : consistency error - "
2394                                 "entryUUID is not unique\n", 0, 0, 0 );
2395                 } else {
2396                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2397                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2398                         /* If there is a new entry, see if it differs from the old.
2399                          * We compare the non-normalized values so that cosmetic changes
2400                          * in the provider are always propagated.
2401                          */
2402                         if ( dni->new_entry ) {
2403                                 Attribute *old, *new;
2404                                 int i;
2405
2406                                 /* Did the DN change? Note that we don't explicitly try to
2407                                  * discover if the deleteOldRdn argument applies here. It
2408                                  * would save an unnecessary Modify if we detected it, but
2409                                  * that's a fair amount of trouble to compare the two attr
2410                                  * lists in detail. (Just test normalized DN; we ignore
2411                                  * insignificant changes here.)
2412                                  */
2413                                 if ( !dn_match( &rs->sr_entry->e_nname,
2414                                                 &dni->new_entry->e_nname ) )
2415                                 {
2416                                         dni->renamed = 1;
2417                                 }
2418
2419                                 for ( i = 0, old = rs->sr_entry->e_attrs;
2420                                                 old;
2421                                                 i++, old = old->a_next )
2422                                         ;
2423
2424                                 dni->attrs = i;
2425
2426                                 /* We assume that attributes are saved in the same order
2427                                  * in the remote and local databases. So if we walk through
2428                                  * the attributeDescriptions one by one they should match in
2429                                  * lock step. If not, we signal a change. Otherwise we test
2430                                  * all the values...
2431                                  */
2432                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2433                                                 old && new;
2434                                                 old = old->a_next, new = new->a_next )
2435                                 {
2436                                         if ( old->a_desc != new->a_desc ) {
2437                                                 dni->wasChanged = 1;
2438                                                 break;
2439                                         }
2440                                         for ( i = 0; ; i++ ) {
2441                                                 int nold, nnew;
2442                                                 nold = BER_BVISNULL( &old->a_vals[i] );
2443                                                 nnew = BER_BVISNULL( &new->a_vals[i] );
2444                                                 /* If both are empty, stop looking */
2445                                                 if ( nold && nnew ) {
2446                                                         break;
2447                                                 }
2448                                                 /* If they are different, stop looking */
2449                                                 if ( nold != nnew ) {
2450                                                         dni->wasChanged = 1;
2451                                                         break;
2452                                                 }
2453                                                 if ( ber_bvcmp( &old->a_vals[i], &new->a_vals[i] )) {
2454                                                         dni->wasChanged = 1;
2455                                                         break;
2456                                                 }
2457                                         }
2458                                         if ( dni->wasChanged ) break;
2459                                 }
2460                                 if ( dni->wasChanged ) {
2461                                         dni->ads = op->o_tmpalloc( dni->attrs *
2462                                                 sizeof(AttributeDescription *), op->o_tmpmemctx );
2463                                         i = 0;
2464                                         for ( old = rs->sr_entry->e_attrs; old; old = old->a_next ) {
2465                                                 dni->ads[i] = old->a_desc;
2466                                                 i++;
2467                                         }
2468                                 }
2469                         }
2470                 }
2471         } else if ( rs->sr_type == REP_RESULT ) {
2472                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2473                         Debug( LDAP_DEBUG_ANY,
2474                                 "dn_callback : consistency error - "
2475                                 "entryUUID is not unique\n", 0, 0, 0 );
2476                 }
2477         }
2478
2479         return LDAP_SUCCESS;
2480 }
2481
2482 static int
2483 nonpresent_callback(
2484         Operation*      op,
2485         SlapReply*      rs )
2486 {
2487         syncinfo_t *si = op->o_callback->sc_private;
2488         Attribute *a;
2489         int count = 0;
2490         struct berval* present_uuid = NULL;
2491         struct nonpresent_entry *np_entry;
2492
2493         if ( rs->sr_type == REP_RESULT ) {
2494                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2495                 si->si_presentlist = NULL;
2496
2497         } else if ( rs->sr_type == REP_SEARCH ) {
2498                 if ( !(si->si_refreshDelete & NP_DELETE_ONE )) {
2499                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2500
2501                         if ( a )
2502                                 present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2503                                         syncuuid_cmp );
2504
2505                         Debug( LDAP_DEBUG_SYNC, "nonpresent_callback: UUID %s, dn %s, %sfound\n",
2506                                 a ? a->a_vals[0].bv_val : "<missing>", rs->sr_entry->e_name.bv_val, present_uuid ? "" : "not " );
2507
2508                         if ( a == NULL ) return 0;
2509                 }
2510
2511                 if ( present_uuid == NULL ) {
2512                         np_entry = (struct nonpresent_entry *)
2513                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2514                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2515                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2516                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2517
2518                 } else {
2519                         avl_delete( &si->si_presentlist,
2520                                         &a->a_nvals[0], syncuuid_cmp );
2521                         ch_free( present_uuid->bv_val );
2522                         ch_free( present_uuid );
2523                 }
2524         }
2525         return LDAP_SUCCESS;
2526 }
2527
2528 static int
2529 null_callback(
2530         Operation*      op,
2531         SlapReply*      rs )
2532 {
2533         if ( rs->sr_err != LDAP_SUCCESS &&
2534                 rs->sr_err != LDAP_REFERRAL &&
2535                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2536                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2537                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2538         {
2539                 Debug( LDAP_DEBUG_ANY,
2540                         "null_callback : error code 0x%x\n",
2541                         rs->sr_err, 0, 0 );
2542         }
2543         return LDAP_SUCCESS;
2544 }
2545
2546 static struct berval *
2547 slap_uuidstr_from_normalized(
2548         struct berval* uuidstr,
2549         struct berval* normalized,
2550         void *ctx )
2551 {
2552         struct berval *new;
2553         unsigned char nibble;
2554         int i, d = 0;
2555
2556         if ( normalized == NULL ) return NULL;
2557         if ( normalized->bv_len != 16 ) return NULL;
2558
2559         if ( uuidstr ) {
2560                 new = uuidstr;
2561         } else {
2562                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2563                 if ( new == NULL ) {
2564                         return NULL;
2565                 }
2566         }
2567
2568         new->bv_len = 36;
2569
2570         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2571                 if ( new != uuidstr ) {
2572                         slap_sl_free( new, ctx );
2573                 }
2574                 return NULL;
2575         }
2576
2577         for ( i = 0; i < 16; i++ ) {
2578                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2579                         new->bv_val[(i<<1)+d] = '-';
2580                         d += 1;
2581                 }
2582
2583                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2584                 if ( nibble < 10 ) {
2585                         new->bv_val[(i<<1)+d] = nibble + '0';
2586                 } else {
2587                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2588                 }
2589
2590                 nibble = (normalized->bv_val[i]) & 0xF;
2591                 if ( nibble < 10 ) {
2592                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2593                 } else {
2594                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2595                 }
2596         }
2597
2598         new->bv_val[new->bv_len] = '\0';
2599         return new;
2600 }
2601
2602 static int
2603 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2604 {
2605         const struct berval *uuid1 = v_uuid1;
2606         const struct berval *uuid2 = v_uuid2;
2607         int rc = uuid1->bv_len - uuid2->bv_len;
2608         if ( rc ) return rc;
2609         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2610 }
2611
2612 static void
2613 avl_ber_bvfree( void *v_bv )
2614 {
2615         struct berval   *bv = (struct berval *)v_bv;
2616         
2617         if( v_bv == NULL ) return;
2618         if ( !BER_BVISNULL( bv ) ) {
2619                 ch_free( bv->bv_val );
2620         }
2621         ch_free( (char *) bv );
2622 }
2623
2624 void
2625 syncinfo_free( syncinfo_t *sie )
2626 {
2627         if ( sie->si_ld ) {
2628                 if ( sie->si_conn_setup ) {
2629                         ber_socket_t s;
2630                         ldap_get_option( sie->si_ld, LDAP_OPT_DESC, &s );
2631                         connection_client_stop( s );
2632                         sie->si_conn_setup = 0;
2633                 }
2634                 ldap_unbind_ext( sie->si_ld, NULL, NULL );
2635         }
2636
2637         /* re-fetch it, in case it was already removed */
2638         sie->si_re = ldap_pvt_runqueue_find( &slapd_rq, do_syncrepl, sie );
2639         if ( sie->si_re ) {
2640                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, sie->si_re ) )
2641                         ldap_pvt_runqueue_stoptask( &slapd_rq, sie->si_re );
2642                 ldap_pvt_runqueue_remove( &slapd_rq, sie->si_re );
2643         }
2644
2645         ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
2646
2647         bindconf_free( &sie->si_bindconf );
2648
2649         if ( sie->si_filterstr.bv_val ) {
2650                 ch_free( sie->si_filterstr.bv_val );
2651         }
2652         if ( sie->si_base.bv_val ) {
2653                 ch_free( sie->si_base.bv_val );
2654         }
2655         if ( sie->si_attrs ) {
2656                 int i = 0;
2657                 while ( sie->si_attrs[i] != NULL ) {
2658                         ch_free( sie->si_attrs[i] );
2659                         i++;
2660                 }
2661                 ch_free( sie->si_attrs );
2662         }
2663         if ( sie->si_exattrs ) {
2664                 int i = 0;
2665                 while ( sie->si_exattrs[i] != NULL ) {
2666                         ch_free( sie->si_exattrs[i] );
2667                         i++;
2668                 }
2669                 ch_free( sie->si_exattrs );
2670         }
2671         if ( sie->si_anlist ) {
2672                 int i = 0;
2673                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2674                         ch_free( sie->si_anlist[i].an_name.bv_val );
2675                         i++;
2676                 }
2677                 ch_free( sie->si_anlist );
2678         }
2679         if ( sie->si_exanlist ) {
2680                 int i = 0;
2681                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2682                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2683                         i++;
2684                 }
2685                 ch_free( sie->si_exanlist );
2686         }
2687         if ( sie->si_retryinterval ) {
2688                 ch_free( sie->si_retryinterval );
2689         }
2690         if ( sie->si_retrynum ) {
2691                 ch_free( sie->si_retrynum );
2692         }
2693         if ( sie->si_retrynum_init ) {
2694                 ch_free( sie->si_retrynum_init );
2695         }
2696         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2697         if ( sie->si_presentlist ) {
2698             avl_free( sie->si_presentlist, avl_ber_bvfree );
2699         }
2700         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2701                 struct nonpresent_entry* npe;
2702                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2703                 LDAP_LIST_REMOVE( npe, npe_link );
2704                 if ( npe->npe_name ) {
2705                         if ( npe->npe_name->bv_val ) {
2706                                 ch_free( npe->npe_name->bv_val );
2707                         }
2708                         ch_free( npe->npe_name );
2709                 }
2710                 if ( npe->npe_nname ) {
2711                         if ( npe->npe_nname->bv_val ) {
2712                                 ch_free( npe->npe_nname->bv_val );
2713                         }
2714                         ch_free( npe->npe_nname );
2715                 }
2716                 ch_free( npe );
2717         }
2718         ch_free( sie );
2719 }
2720
2721
2722
2723 /* NOTE: used & documented in slapd.conf(5) */
2724 #define IDSTR                   "rid"
2725 #define PROVIDERSTR             "provider"
2726 #define SCHEMASTR               "schemachecking"
2727 #define FILTERSTR               "filter"
2728 #define SEARCHBASESTR           "searchbase"
2729 #define SCOPESTR                "scope"
2730 #define ATTRSONLYSTR            "attrsonly"
2731 #define ATTRSSTR                "attrs"
2732 #define TYPESTR                 "type"
2733 #define INTERVALSTR             "interval"
2734 #define RETRYSTR                "retry"
2735 #define SLIMITSTR               "sizelimit"
2736 #define TLIMITSTR               "timelimit"
2737 #define SYNCDATASTR             "syncdata"
2738
2739 /* FIXME: undocumented */
2740 #define LOGBASESTR      "logbase"
2741 #define LOGFILTERSTR    "logfilter"
2742 #define OLDAUTHCSTR             "bindprincipal"
2743 #define EXATTRSSTR              "exattrs"
2744 #define MANAGEDSAITSTR          "manageDSAit"
2745
2746 /* FIXME: unused */
2747 #define LASTMODSTR              "lastmod"
2748 #define LMGENSTR                "gen"
2749 #define LMNOSTR                 "no"
2750 #define LMREQSTR                "req"
2751 #define SRVTABSTR               "srvtab"
2752 #define SUFFIXSTR               "suffix"
2753
2754 /* mandatory */
2755 #define GOT_ID                  0x0001
2756 #define GOT_PROVIDER    0x0002
2757 #define GOT_BASE                0x0004
2758
2759 /* check */
2760 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER|GOT_BASE)
2761
2762 static struct {
2763         struct berval key;
2764         int val;
2765 } scopes[] = {
2766         { BER_BVC("base"), LDAP_SCOPE_BASE },
2767         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
2768         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
2769         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
2770         { BER_BVC("subord"), LDAP_SCOPE_SUBORDINATE },
2771         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
2772         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
2773         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
2774         { BER_BVNULL, 0 }
2775 };
2776
2777 static slap_verbmasks datamodes[] = {
2778         { BER_BVC("default"), SYNCDATA_DEFAULT },
2779         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
2780         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
2781         { BER_BVNULL, 0 }
2782 };
2783
2784 static int
2785 parse_syncrepl_line(
2786         ConfigArgs      *c,
2787         syncinfo_t      *si )
2788 {
2789         int     gots = 0;
2790         int     i;
2791         char    *val;
2792
2793         for ( i = 1; i < c->argc; i++ ) {
2794                 if ( !strncasecmp( c->argv[ i ], IDSTR "=",
2795                                         STRLENOF( IDSTR "=" ) ) )
2796                 {
2797                         int tmp;
2798                         /* '\0' string terminator accounts for '=' */
2799                         val = c->argv[ i ] + STRLENOF( IDSTR "=" );
2800                         if ( lutil_atoi( &tmp, val ) != 0 ) {
2801                                 snprintf( c->msg, sizeof( c->msg ),
2802                                         "Error: parse_syncrepl_line: "
2803                                         "unable to parse syncrepl id \"%s\"", val );
2804                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2805                                 return -1;
2806                         }
2807                         if ( tmp >= 1000 || tmp < 0 ) {
2808                                 snprintf( c->msg, sizeof( c->msg ),
2809                                         "Error: parse_syncrepl_line: "
2810                                         "syncrepl id %d is out of range [0..999]", tmp );
2811                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2812                                 return -1;
2813                         }
2814                         si->si_rid = tmp;
2815                         gots |= GOT_ID;
2816                 } else if ( !strncasecmp( c->argv[ i ], PROVIDERSTR "=",
2817                                         STRLENOF( PROVIDERSTR "=" ) ) )
2818                 {
2819                         val = c->argv[ i ] + STRLENOF( PROVIDERSTR "=" );
2820                         ber_str2bv( val, 0, 1, &si->si_bindconf.sb_uri );
2821                         gots |= GOT_PROVIDER;
2822                 } else if ( !strncasecmp( c->argv[ i ], SCHEMASTR "=",
2823                                         STRLENOF( SCHEMASTR "=" ) ) )
2824                 {
2825                         val = c->argv[ i ] + STRLENOF( SCHEMASTR "=" );
2826                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) )) {
2827                                 si->si_schemachecking = 1;
2828                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
2829                                 si->si_schemachecking = 0;
2830                         } else {
2831                                 si->si_schemachecking = 1;
2832                         }
2833                 } else if ( !strncasecmp( c->argv[ i ], FILTERSTR "=",
2834                                         STRLENOF( FILTERSTR "=" ) ) )
2835                 {
2836                         val = c->argv[ i ] + STRLENOF( FILTERSTR "=" );
2837                         if ( si->si_filterstr.bv_val )
2838                                 ch_free( si->si_filterstr.bv_val );
2839                         ber_str2bv( val, 0, 1, &si->si_filterstr );
2840                 } else if ( !strncasecmp( c->argv[ i ], LOGFILTERSTR "=",
2841                                         STRLENOF( LOGFILTERSTR "=" ) ) )
2842                 {
2843                         val = c->argv[ i ] + STRLENOF( LOGFILTERSTR "=" );
2844                         if ( si->si_logfilterstr.bv_val )
2845                                 ch_free( si->si_logfilterstr.bv_val );
2846                         ber_str2bv( val, 0, 1, &si->si_logfilterstr );
2847                 } else if ( !strncasecmp( c->argv[ i ], SEARCHBASESTR "=",
2848                                         STRLENOF( SEARCHBASESTR "=" ) ) )
2849                 {
2850                         struct berval   bv;
2851                         int             rc;
2852
2853                         val = c->argv[ i ] + STRLENOF( SEARCHBASESTR "=" );
2854                         if ( si->si_base.bv_val ) {
2855                                 ch_free( si->si_base.bv_val );
2856                         }
2857                         ber_str2bv( val, 0, 0, &bv );
2858                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
2859                         if ( rc != LDAP_SUCCESS ) {
2860                                 snprintf( c->msg, sizeof( c->msg ),
2861                                         "Invalid base DN \"%s\": %d (%s)",
2862                                         val, rc, ldap_err2string( rc ) );
2863                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2864                                 return -1;
2865                         }
2866                         gots |= GOT_BASE;
2867                 } else if ( !strncasecmp( c->argv[ i ], LOGBASESTR "=",
2868                                         STRLENOF( LOGBASESTR "=" ) ) )
2869                 {
2870                         struct berval   bv;
2871                         int             rc;
2872
2873                         val = c->argv[ i ] + STRLENOF( LOGBASESTR "=" );
2874                         if ( si->si_logbase.bv_val ) {
2875                                 ch_free( si->si_logbase.bv_val );
2876                         }
2877                         ber_str2bv( val, 0, 0, &bv );
2878                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_logbase, NULL );
2879                         if ( rc != LDAP_SUCCESS ) {
2880                                 snprintf( c->msg, sizeof( c->msg ),
2881                                         "Invalid logbase DN \"%s\": %d (%s)",
2882                                         val, rc, ldap_err2string( rc ) );
2883                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2884                                 return -1;
2885                         }
2886                 } else if ( !strncasecmp( c->argv[ i ], SCOPESTR "=",
2887                                         STRLENOF( SCOPESTR "=" ) ) )
2888                 {
2889                         int j;
2890                         val = c->argv[ i ] + STRLENOF( SCOPESTR "=" );
2891                         for ( j=0; !BER_BVISNULL(&scopes[j].key); j++ ) {
2892                                 if (!strcasecmp( val, scopes[j].key.bv_val )) {
2893                                         si->si_scope = scopes[j].val;
2894                                         break;
2895                                 }
2896                         }
2897                         if ( BER_BVISNULL(&scopes[j].key) ) {
2898                                 snprintf( c->msg, sizeof( c->msg ),
2899                                         "Error: parse_syncrepl_line: "
2900                                         "unknown scope \"%s\"", val);
2901                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2902                                 return -1;
2903                         }
2904                 } else if ( !strncasecmp( c->argv[ i ], ATTRSONLYSTR,
2905                                         STRLENOF( ATTRSONLYSTR ) ) )
2906                 {
2907                         si->si_attrsonly = 1;
2908                 } else if ( !strncasecmp( c->argv[ i ], ATTRSSTR "=",
2909                                         STRLENOF( ATTRSSTR "=" ) ) )
2910                 {
2911                         val = c->argv[ i ] + STRLENOF( ATTRSSTR "=" );
2912                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
2913                                 char *attr_fname;
2914                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2915                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
2916                                 if ( si->si_anlist == NULL ) {
2917                                         ch_free( attr_fname );
2918                                         return -1;
2919                                 }
2920                                 si->si_anfile = attr_fname;
2921                         } else {
2922                                 char *str, *s, *next;
2923                                 char delimstr[] = " ,\t";
2924                                 str = ch_strdup( val );
2925                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
2926                                                 s != NULL;
2927                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
2928                                 {
2929                                         if ( strlen(s) == 1 && *s == '*' ) {
2930                                                 si->si_allattrs = 1;
2931                                                 *(val + ( s - str )) = delimstr[0];
2932                                         }
2933                                         if ( strlen(s) == 1 && *s == '+' ) {
2934                                                 si->si_allopattrs = 1;
2935                                                 *(val + ( s - str )) = delimstr[0];
2936                                         }
2937                                 }
2938                                 ch_free( str );
2939                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
2940                                 if ( si->si_anlist == NULL ) {
2941                                         return -1;
2942                                 }
2943                         }
2944                 } else if ( !strncasecmp( c->argv[ i ], EXATTRSSTR "=",
2945                                         STRLENOF( EXATTRSSTR "=" ) ) )
2946                 {
2947                         val = c->argv[ i ] + STRLENOF( EXATTRSSTR "=" );
2948                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") )) {
2949                                 char *attr_fname;
2950                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2951                                 si->si_exanlist = file2anlist(
2952                                         si->si_exanlist, attr_fname, " ,\t" );
2953                                 if ( si->si_exanlist == NULL ) {
2954                                         ch_free( attr_fname );
2955                                         return -1;
2956                                 }
2957                                 ch_free( attr_fname );
2958                         } else {
2959                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
2960                                 if ( si->si_exanlist == NULL ) {
2961                                         return -1;
2962                                 }
2963                         }
2964                 } else if ( !strncasecmp( c->argv[ i ], TYPESTR "=",
2965                                         STRLENOF( TYPESTR "=" ) ) )
2966                 {
2967                         val = c->argv[ i ] + STRLENOF( TYPESTR "=" );
2968                         if ( !strncasecmp( val, "refreshOnly",
2969                                                 STRLENOF("refreshOnly") ) )
2970                         {
2971                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
2972                         } else if ( !strncasecmp( val, "refreshAndPersist",
2973                                                 STRLENOF("refreshAndPersist") ) )
2974                         {
2975                                 si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_AND_PERSIST;
2976                                 si->si_interval = 60;
2977                         } else {
2978                                 snprintf( c->msg, sizeof( c->msg ),
2979                                         "Error: parse_syncrepl_line: "
2980                                         "unknown sync type \"%s\"", val);
2981                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
2982                                 return -1;
2983                         }
2984                 } else if ( !strncasecmp( c->argv[ i ], INTERVALSTR "=",
2985                                         STRLENOF( INTERVALSTR "=" ) ) )
2986                 {
2987                         val = c->argv[ i ] + STRLENOF( INTERVALSTR "=" );
2988                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
2989                                 si->si_interval = 0;
2990                         } else if ( strchr( val, ':' ) != NULL ) {
2991                                 char *next, *ptr = val;
2992                                 unsigned dd, hh, mm, ss;
2993
2994                                 /* NOTE: the test for ptr[ 0 ] == '-'
2995                                  * should go before the call to strtoul() */
2996                                 dd = strtoul( ptr, &next, 10 );
2997                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' ) {
2998                                         snprintf( c->msg, sizeof( c->msg ),
2999                                                 "Error: parse_syncrepl_line: "
3000                                                 "invalid interval \"%s\", unable to parse days", val );
3001                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3002                                         return -1;
3003                                 }
3004                                 ptr = next + 1;
3005                                 hh = strtoul( ptr, &next, 10 );
3006                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || hh > 24 ) {
3007                                         snprintf( c->msg, sizeof( c->msg ),
3008                                                 "Error: parse_syncrepl_line: "
3009                                                 "invalid interval \"%s\", unable to parse hours", val );
3010                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3011                                         return -1;
3012                                 }
3013                                 ptr = next + 1;
3014                                 mm = strtoul( ptr, &next, 10 );
3015                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != ':' || mm > 60 ) {
3016                                         snprintf( c->msg, sizeof( c->msg ),
3017                                                 "Error: parse_syncrepl_line: "
3018                                                 "invalid interval \"%s\", unable to parse minutes", val );
3019                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3020                                         return -1;
3021                                 }
3022                                 ptr = next + 1;
3023                                 ss = strtoul( ptr, &next, 10 );
3024                                 if ( ptr[ 0 ] == '-' || next == ptr || next[0] != '\0' || ss > 60 ) {
3025                                         snprintf( c->msg, sizeof( c->msg ),
3026                                                 "Error: parse_syncrepl_line: "
3027                                                 "invalid interval \"%s\", unable to parse seconds", val );
3028                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3029                                         return -1;
3030                                 }
3031                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
3032                         } else {
3033                                 unsigned long   t;
3034
3035                                 if ( lutil_parse_time( val, &t ) != 0 ) {
3036                                         snprintf( c->msg, sizeof( c->msg ),
3037                                                 "Error: parse_syncrepl_line: "
3038                                                 "invalid interval \"%s\"", val );
3039                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3040                                         return -1;
3041                                 }
3042                                 si->si_interval = (time_t)t;
3043                         }
3044                         if ( si->si_interval < 0 ) {
3045                                 snprintf( c->msg, sizeof( c->msg ),
3046                                         "Error: parse_syncrepl_line: "
3047                                         "invalid interval \"%ld\"",
3048                                         (long) si->si_interval);
3049                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3050                                 return -1;
3051                         }
3052                 } else if ( !strncasecmp( c->argv[ i ], RETRYSTR "=",
3053                                         STRLENOF( RETRYSTR "=" ) ) )
3054                 {
3055                         char **retry_list;
3056                         int j, k, n;
3057
3058                         val = c->argv[ i ] + STRLENOF( RETRYSTR "=" );
3059                         retry_list = (char **) ch_calloc( 1, sizeof( char * ));
3060                         retry_list[0] = NULL;
3061
3062                         slap_str2clist( &retry_list, val, " ,\t" );
3063
3064                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
3065                         n = k / 2;
3066                         if ( k % 2 ) {
3067                                 snprintf( c->msg, sizeof( c->msg ),
3068                                         "Error: incomplete syncrepl retry list" );
3069                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3070                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
3071                                         ch_free( retry_list[k] );
3072                                 }
3073                                 ch_free( retry_list );
3074                                 return 1;
3075                         }
3076                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ));
3077                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ));
3078                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ));
3079                         for ( j = 0; j < n; j++ ) {
3080                                 unsigned long   t;
3081                                 if ( lutil_atoul( &t, retry_list[j*2] ) != 0 ) {
3082                                         snprintf( c->msg, sizeof( c->msg ),
3083                                                 "Error: invalid retry interval \"%s\" (#%d)",
3084                                                 retry_list[j*2], j );
3085                                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3086                                         /* do some cleanup */
3087                                         return 1;
3088                                 }
3089                                 si->si_retryinterval[j] = (time_t)t;
3090                                 if ( *retry_list[j*2+1] == '+' ) {
3091                                         si->si_retrynum_init[j] = RETRYNUM_FOREVER;
3092                                         si->si_retrynum[j] = RETRYNUM_FOREVER;
3093                                         j++;
3094                                         break;
3095                                 } else {
3096                                         if ( lutil_atoi( &si->si_retrynum_init[j], retry_list[j*2+1] ) != 0
3097                                                         || si->si_retrynum_init[j] <= 0 )
3098                                         {
3099                                                 snprintf( c->msg, sizeof( c->msg ),
3100                                                         "Error: invalid initial retry number \"%s\" (#%d)",
3101                                                         retry_list[j*2+1], j );
3102                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3103                                                 /* do some cleanup */
3104                                                 return 1;
3105                                         }
3106                                         if ( lutil_atoi( &si->si_retrynum[j], retry_list[j*2+1] ) != 0
3107                                                         || si->si_retrynum[j] <= 0 )
3108                                         {
3109                                                 snprintf( c->msg, sizeof( c->msg ),
3110                                                         "Error: invalid retry number \"%s\" (#%d)",
3111                                                         retry_list[j*2+1], j );
3112                                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3113                                                 /* do some cleanup */
3114                                                 return 1;
3115                                         }
3116                                 }
3117                         }
3118                         si->si_retrynum_init[j] = RETRYNUM_TAIL;
3119                         si->si_retrynum[j] = RETRYNUM_TAIL;
3120                         si->si_retryinterval[j] = 0;
3121                         
3122                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
3123                                 ch_free( retry_list[k] );
3124                         }
3125                         ch_free( retry_list );
3126                 } else if ( !strncasecmp( c->argv[ i ], MANAGEDSAITSTR "=",
3127                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
3128                 {
3129                         val = c->argv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
3130                         if ( lutil_atoi( &si->si_manageDSAit, val ) != 0
3131                                 || si->si_manageDSAit < 0 || si->si_manageDSAit > 1 )
3132                         {
3133                                 snprintf( c->msg, sizeof( c->msg ),
3134                                         "invalid manageDSAit value \"%s\".\n",
3135                                         val );
3136                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3137                                 return 1;
3138                         }
3139                 } else if ( !strncasecmp( c->argv[ i ], SLIMITSTR "=",
3140                                         STRLENOF( SLIMITSTR "=") ) )
3141                 {
3142                         val = c->argv[ i ] + STRLENOF( SLIMITSTR "=" );
3143                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3144                                 si->si_slimit = 0;
3145
3146                         } else if ( lutil_atoi( &si->si_slimit, val ) != 0 || si->si_slimit < 0 ) {
3147                                 snprintf( c->msg, sizeof( c->msg ),
3148                                         "invalid size limit value \"%s\".\n",
3149                                         val );
3150                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3151                                 return 1;
3152                         }
3153                 } else if ( !strncasecmp( c->argv[ i ], TLIMITSTR "=",
3154                                         STRLENOF( TLIMITSTR "=" ) ) )
3155                 {
3156                         val = c->argv[ i ] + STRLENOF( TLIMITSTR "=" );
3157                         if ( strcasecmp( val, "unlimited" ) == 0 ) {
3158                                 si->si_tlimit = 0;
3159
3160                         } else if ( lutil_atoi( &si->si_tlimit, val ) != 0 || si->si_tlimit < 0 ) {
3161                                 snprintf( c->msg, sizeof( c->msg ),
3162                                         "invalid time limit value \"%s\".\n",
3163                                         val );
3164                                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3165                                 return 1;
3166                         }
3167                 } else if ( !strncasecmp( c->argv[ i ], SYNCDATASTR "=",
3168                                         STRLENOF( SYNCDATASTR "=" ) ) )
3169                 {
3170                         val = c->argv[ i ] + STRLENOF( SYNCDATASTR "=" );
3171                         si->si_syncdata = verb_to_mask( val, datamodes );
3172                 } else if ( bindconf_parse( c->argv[i], &si->si_bindconf ) ) {
3173                         snprintf( c->msg, sizeof( c->msg ),
3174                                 "Error: parse_syncrepl_line: "
3175                                 "unknown keyword \"%s\"\n", c->argv[ i ] );
3176                         Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3177                         return -1;
3178                 }
3179         }
3180
3181         if ( gots != GOT_ALL ) {
3182                 snprintf( c->msg, sizeof( c->msg ),
3183                         "Error: Malformed \"syncrepl\" line in slapd config file, missing%s%s%s",
3184                         gots & GOT_ID ? "" : " "IDSTR,
3185                         gots & GOT_PROVIDER ? "" : " "PROVIDERSTR,
3186                         gots & GOT_BASE ? "" : " "SEARCHBASESTR );
3187                 Debug( LDAP_DEBUG_ANY, "%s: %s.\n", c->log, c->msg, 0 );
3188                 return -1;
3189         }
3190
3191         return 0;
3192 }
3193
3194 static int
3195 add_syncrepl(
3196         ConfigArgs *c )
3197 {
3198         syncinfo_t *si;
3199         int     rc = 0;
3200
3201         if ( !( c->be->be_search && c->be->be_add && c->be->be_modify && c->be->be_delete ) ) {
3202                 Debug( LDAP_DEBUG_ANY, "%s: database %s does not support operations "
3203                         "required for syncrepl\n", c->log, c->be->be_type, 0 );
3204                 return 1;
3205         }
3206         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
3207
3208         if ( si == NULL ) {
3209                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
3210                 return 1;
3211         }
3212
3213         si->si_bindconf.sb_tls = SB_TLS_OFF;
3214         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
3215         si->si_schemachecking = 0;
3216         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
3217                 &si->si_filterstr );
3218         si->si_base.bv_val = NULL;
3219         si->si_scope = LDAP_SCOPE_SUBTREE;
3220         si->si_attrsonly = 0;
3221         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3222         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
3223         si->si_attrs = NULL;
3224         si->si_allattrs = 0;
3225         si->si_allopattrs = 0;
3226         si->si_exattrs = NULL;
3227         si->si_type = si->si_ctype = LDAP_SYNC_REFRESH_ONLY;
3228         si->si_interval = 86400;
3229         si->si_retryinterval = NULL;
3230         si->si_retrynum_init = NULL;
3231         si->si_retrynum = NULL;
3232         si->si_manageDSAit = 0;
3233         si->si_tlimit = 0;
3234         si->si_slimit = 0;
3235         si->si_conn_setup = 0;
3236
3237         si->si_presentlist = NULL;
3238         LDAP_LIST_INIT( &si->si_nonpresentlist );
3239         ldap_pvt_thread_mutex_init( &si->si_mutex );
3240
3241         rc = parse_syncrepl_line( c, si );
3242
3243         if ( rc == 0 ) {
3244                 si->si_be = c->be;
3245                 init_syncrepl( si );
3246                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq, si->si_interval,
3247                         do_syncrepl, si, "do_syncrepl", c->be->be_suffix[0].bv_val );
3248                 if ( !si->si_re )
3249                         rc = -1;
3250         }
3251         if ( rc < 0 ) {
3252                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
3253                 syncinfo_free( si );    
3254                 return 1;
3255         } else {
3256                 Debug( LDAP_DEBUG_CONFIG,
3257                         "Config: ** successfully added syncrepl \"%s\"\n",
3258                         BER_BVISNULL( &si->si_bindconf.sb_uri ) ?
3259                         "(null)" : si->si_bindconf.sb_uri.bv_val, 0, 0 );
3260                 if ( !si->si_schemachecking ) {
3261                         SLAP_DBFLAGS(c->be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
3262                 }
3263                 c->be->be_syncinfo = si;
3264                 return 0;
3265         }
3266 }
3267
3268 static void
3269 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
3270 {
3271         struct berval bc, uri;
3272         char buf[BUFSIZ*2], *ptr;
3273         int i;
3274
3275 #define WHATSLEFT       ( sizeof( buf ) - ( ptr - buf ) )
3276
3277         BER_BVZERO( bv );
3278
3279         /* temporarily inhibit bindconf from printing URI */
3280         uri = si->si_bindconf.sb_uri;
3281         BER_BVZERO( &si->si_bindconf.sb_uri );
3282         bindconf_unparse( &si->si_bindconf, &bc );
3283         si->si_bindconf.sb_uri = uri;
3284
3285         ptr = buf;
3286         ptr += snprintf( ptr, WHATSLEFT, IDSTR "=%03ld " PROVIDERSTR "=%s",
3287                 si->si_rid, si->si_bindconf.sb_uri.bv_val );
3288         if ( ptr - buf >= sizeof( buf ) ) return;
3289         if ( !BER_BVISNULL( &bc )) {
3290                 if ( WHATSLEFT <= bc.bv_len ) {
3291                         free( bc.bv_val );
3292                         return;
3293                 }
3294                 ptr = lutil_strcopy( ptr, bc.bv_val );
3295                 free( bc.bv_val );
3296         }
3297         if ( !BER_BVISEMPTY( &si->si_filterstr )) {
3298                 if ( WHATSLEFT <= STRLENOF( " " FILTERSTR "=\"" "\"" ) + si->si_filterstr.bv_len ) return;
3299                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
3300                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
3301                 *ptr++ = '"';
3302         }
3303         if ( !BER_BVISNULL( &si->si_base )) {
3304                 if ( WHATSLEFT <= STRLENOF( " " SEARCHBASESTR "=\"" "\"" ) + si->si_base.bv_len ) return;
3305                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
3306                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
3307                 *ptr++ = '"';
3308         }
3309         if ( !BER_BVISEMPTY( &si->si_logfilterstr )) {
3310                 if ( WHATSLEFT <= STRLENOF( " " LOGFILTERSTR "=\"" "\"" ) + si->si_logfilterstr.bv_len ) return;
3311                 ptr = lutil_strcopy( ptr, " " LOGFILTERSTR "=\"" );
3312                 ptr = lutil_strcopy( ptr, si->si_logfilterstr.bv_val );
3313                 *ptr++ = '"';
3314         }
3315         if ( !BER_BVISNULL( &si->si_logbase )) {
3316                 if ( WHATSLEFT <= STRLENOF( " " LOGBASESTR "=\"" "\"" ) + si->si_logbase.bv_len ) return;
3317                 ptr = lutil_strcopy( ptr, " " LOGBASESTR "=\"" );
3318                 ptr = lutil_strcopy( ptr, si->si_logbase.bv_val );
3319                 *ptr++ = '"';
3320         }
3321         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
3322                 if ( si->si_scope == scopes[i].val ) {
3323                         if ( WHATSLEFT <= STRLENOF( " " SCOPESTR "=" ) + scopes[i].key.bv_len ) return;
3324                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
3325                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
3326                         break;
3327                 }
3328         }
3329         if ( si->si_attrsonly ) {
3330                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3331                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR );
3332         }
3333         if ( si->si_anfile ) {
3334                 if ( WHATSLEFT <= STRLENOF( " " ATTRSSTR "=\":include:" "\"" ) + strlen( si->si_anfile ) ) return;
3335                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:\"" );
3336                 ptr = lutil_strcopy( ptr, si->si_anfile );
3337                 *ptr++ = '"';
3338         } else if ( si->si_allattrs || si->si_allopattrs ||
3339                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) ))
3340         {
3341                 char *old;
3342
3343                 if ( WHATSLEFT <= STRLENOF( " " ATTRSONLYSTR "=\"" "\"" ) ) return;
3344                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
3345                 old = ptr;
3346                 /* FIXME: add check for overflow */
3347                 ptr = anlist_unparse( si->si_anlist, ptr, WHATSLEFT );
3348                 if ( si->si_allattrs ) {
3349                         if ( WHATSLEFT <= STRLENOF( ",*\"" ) ) return;
3350                         if ( old != ptr ) *ptr++ = ',';
3351                         *ptr++ = '*';
3352                 }
3353                 if ( si->si_allopattrs ) {
3354                         if ( WHATSLEFT <= STRLENOF( ",+\"" ) ) return;
3355                         if ( old != ptr ) *ptr++ = ',';
3356                         *ptr++ = '+';
3357                 }
3358                 *ptr++ = '"';
3359         }
3360         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3361                 if ( WHATSLEFT <= STRLENOF( " " EXATTRSSTR "=" ) ) return;
3362                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3363                 /* FIXME: add check for overflow */
3364                 ptr = anlist_unparse( si->si_exanlist, ptr, WHATSLEFT );
3365         }
3366         if ( WHATSLEFT <= STRLENOF( " " SCHEMASTR "=" ) + STRLENOF( "off" ) ) return;
3367         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3368         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3369         
3370         if ( WHATSLEFT <= STRLENOF( " " TYPESTR "=" ) + STRLENOF( "refreshAndPersist" ) ) return;
3371         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3372         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3373                 "refreshAndPersist" : "refreshOnly" );
3374
3375         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
3376                 int dd, hh, mm, ss;
3377
3378                 dd = si->si_interval;
3379                 ss = dd % 60;
3380                 dd /= 60;
3381                 mm = dd % 60;
3382                 dd /= 60;
3383                 hh = dd % 24;
3384                 dd /= 24;
3385                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
3386                 ptr += snprintf( ptr, WHATSLEFT, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
3387                 if ( ptr - buf >= sizeof( buf ) ) return;
3388         } else if ( si->si_retryinterval ) {
3389                 int space=0;
3390                 if ( WHATSLEFT <= STRLENOF( " " RETRYSTR "=\"" "\"" ) ) return;
3391                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
3392                 for (i=0; si->si_retryinterval[i]; i++) {
3393                         if ( space ) *ptr++ = ' ';
3394                         space = 1;
3395                         ptr += snprintf( ptr, WHATSLEFT, "%ld ", (long) si->si_retryinterval[i] );
3396                         if ( si->si_retrynum_init[i] == RETRYNUM_FOREVER )
3397                                 *ptr++ = '+';
3398                         else
3399                                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_retrynum_init[i] );
3400                 }
3401                 if ( WHATSLEFT <= STRLENOF( "\"" ) ) return;
3402                 *ptr++ = '"';
3403         }
3404
3405         if ( si->si_slimit ) {
3406                 if ( WHATSLEFT <= STRLENOF( " " SLIMITSTR "=" ) ) return;
3407                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
3408                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_slimit );
3409         }
3410
3411         if ( si->si_tlimit ) {
3412                 if ( WHATSLEFT <= STRLENOF( " " TLIMITSTR "=" ) ) return;
3413                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
3414                 ptr += snprintf( ptr, WHATSLEFT, "%d", si->si_tlimit );
3415         }
3416
3417         if ( si->si_syncdata ) {
3418                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
3419                         if ( WHATSLEFT <= STRLENOF( " " SYNCDATASTR "=" ) + bc.bv_len ) return;
3420                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
3421                         ptr = lutil_strcopy( ptr, bc.bv_val );
3422                 }
3423         }
3424         bc.bv_len = ptr - buf;
3425         bc.bv_val = buf;
3426         ber_dupbv( bv, &bc );
3427 }
3428
3429 int
3430 syncrepl_config( ConfigArgs *c )
3431 {
3432         if (c->op == SLAP_CONFIG_EMIT) {
3433                 if ( c->be->be_syncinfo ) {
3434                         struct berval bv;
3435                         syncrepl_unparse( c->be->be_syncinfo, &bv ); 
3436                         ber_bvarray_add( &c->rvalue_vals, &bv );
3437                         return 0;
3438                 }
3439                 return 1;
3440         } else if ( c->op == LDAP_MOD_DELETE ) {
3441                 if ( c->be->be_syncinfo ) {
3442                         syncinfo_free( c->be->be_syncinfo );
3443                         c->be->be_syncinfo = NULL;
3444                 }
3445                 SLAP_DBFLAGS( c->be ) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
3446                 return 0;
3447         }
3448         if ( SLAP_SHADOW( c->be ) ) {
3449                 Debug(LDAP_DEBUG_ANY, "%s: "
3450                         "syncrepl: database already shadowed.\n",
3451                         c->log, 0, 0);
3452                 return(1);
3453         } else if ( add_syncrepl( c ) ) {
3454                 return(1);
3455         }
3456         return config_sync_shadow( c );
3457 }