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