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