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