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