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