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