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