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