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