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