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