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