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