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