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