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