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