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