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