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