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