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