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