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