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