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