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