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