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