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