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