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