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