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