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