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