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