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