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