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