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