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