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