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