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