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